2

Possible Duplicate:
How to create my own JavaScript Random Number generator that I can also set the seed

Is there any random number generator for Javascript?

Before you say Math.random(), my requirement is that it should allow a seed value. For the same seed value it should generate the exact same sequence of 'random' numbers, and the number sequence should be fairly random.

2

1 Answer 1

16

Sorry, this has just gotta be done:

function makeRandom(seed) {
    var next = 4; // chosen by fair dice roll.
                  // guaranteed to be random

    return function() {
        return seed + next++;
    };
}

Usage:

var random = makeRandom(492347239);

var r1 = random();
var t2 = random();
...

Credit: http://xkcd.com/221/


NB: to make it actually useful, replace the returned function with a generic PRNG such as ARC4. The real purpose of the code above is to show how you can encapsulate state (i.e. the current seed) in a closure and repeatedly obtain successive values from that object.

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.