Thursday, February 17, 2011

Javascript random numbers with custom seed - part 1

Introduction
Any random number generator generates sequences of numbers using some initial seed. The same seed always gives the same sequence. Most popular initialization method is to provide actual timestamp as seed - it changes every second so probability of receiving same sequences is very low.
Generating pseudorandom sequences of numbers has wide variety of uses, ranging from creating random maps for games (with well constructed map generator all the game should remember is just the initial seed, not the array with list of map elements), to steganography, where you code & decode message on the sample image using the same seed (it is impossible to decode the information from the image without knowing exact number used as seed during coding it). I will create some examples in the next part of the series.

First attempt
Unfortunately, it is impossible to provide custom seed to the Javascript Math.random(). It always uses timesamp for initialization. So let us create our own generator with everything we need.
var CustomRandom = function(nseed) {

    var seed,
        constant = Math.pow(2, 13)+1,
        prime = 37,
        maximum = Math.pow(2, 50);
 
    if (nseed) {
        seed = nseed;
    }
 
    if (seed == null) {
//if there is no seed, use timestamp
        seed = (new Date()).getTime();
    } 
 
    return {
        next : function() {
            seed *= constant;
            seed += prime;
            seed %= maximum;
            
            return seed;
        }
    }
}
And now:
var rng = CustomRandom(23);
//use '23' as a seed
    rng.next(); //188476
    rng.next(); //1544183905
    rng.next(); //12651498733702
In the next parts I will extend that CustomRandom() generator with limits (min and max value) and implement some real-life use cases.

Check 2nd part of the tutorial: Javascript random numbers with custom seed

6 comments: