3

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.

Community
  • 1
  • 1
AppleGrew
  • 9,302
  • 24
  • 80
  • 124
  • A similar question here on StackOverflow([How to create my own JavaScript Random Number generator that I can also set the seed](http://stackoverflow.com/questions/424292/how-to-create-my-own-javascript-random-number-generator-that-i-can-also-set-the-s)) gave this website which talks about it: http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html – Levi Morrison Jun 21 '11 at 20:24
  • Yup this is duplicate. StackOverflow's search engine sucks. Whatever I googled with gave all the results I didn't need. – AppleGrew Jun 23 '11 at 06:44

1 Answers1

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495