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开发者_JAVA技巧 of 'random' numbers, and the number sequence should be fairly random.
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.
精彩评论