Random number generator for hack cpu?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Random number generator for hack cpu?

JavaJack
I haven't yet been able to Google up a random number generator that DOESN'T rely on bitshifting. Didn't see any mentioned on this forum, either, although I may have missed it.

A random number generator seems like a must-have for most game-oriented projects. Does anybody have a link or tip that might help here?
Reply | Threaded
Open this post in threaded view
|

Re: Random number generator for hack cpu?

cadet1620
Administrator
Here's the quick and dirty hack I wrote for my game. Well distributed but totally non-random. I seeded it by putting up a "Hit return to play" message and continuously incrementing a counter while waiting for the enter key. The call Random.setSeed(counter).

// Copyright 2012 Mark Armbrust. Permission granted for educational use.

/** Random.jack -- A not so random PRNG. */

class Random {
    static int seed;
    
    function void setSeed(int newSeed) {
        let seed = newSeed;
        return;
    }

    function int rand() {
        /** return a random number in the range 0..32767 */
        let seed = seed + 20251;
        if (seed < 0) {
            let seed = seed - 32767 - 1;
        }
        return seed;
    }

    function int randRange(int range) {
        /** return a random number in the range 0..range */
        var int mask;
        var int ret;
        let mask = 1;
        while (mask < range) {
            let mask = mask * 2 + 1;
        }
        let ret = Random.rand() & mask;
        while (ret > range) {
            let ret = Random.rand() & mask;
        }
        return ret;
    }

}

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: Random number generator for hack cpu?

JavaJack
Cool.

For what it's worth, I got less repeatey results for randRange by doing "rand() / (32767/range)".