开发者

Any pseudo random number generator in Javascript? [duplicate]

开发者 https://www.devze.com 2023-03-14 17:15 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to create my own JavaScript Random Number generator that I can also set the seed
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号