JavaScript Random Numbers
By default, the random function returns a random number between zero and 1.
In that state, you can't really do anything with the number. We want to have an
integer between zero and a set number. The first step to fixing this is using
multiplication. If you want a number between zero and 4 (5 random numbers),
multiply the result of the Math.random() function by 5:
var ran_number= Math.random()*5;
To clean up those decimals and get just the integers, we use the Math.floor()
function (which removes anything after the decimal and leaves the integer
portion of the number) for the result (0-4):
var ran_number=Math.floor(Math.random()*5);
The random number returned is between 0 and 4, which is 5 different
possibilities, the 0 is array friendly where 1 - 5 would not be.
Keeping the random numbers in line with the array numbers will save some
headaches as to when you should add or subtract the number one to get it
working.
You may be curious as to why Math.floor(), instead of Math.round(), is used.
While both successfully round off its containing parameter to an integer
within the designated range, Math.floor does so more "evenly", so the
resulting integer isn't lopsided towards either end of the number spectrum.
In other words, a more random number is returned using Math.floor().
//Random Number Generator Pulic Domain Code (Central Randomizer)
//http://www.msc.cornell.edu/~houle/javascript/randomizer.html
//To create a random floating point number use: rnd()
//To create a random integer between 1 and 10, use: rand(10)
//To create a random integer between 0 and 25, use: rand(26)-1;
rnd.today=new Date();
rnd.seed=rnd.today.getTime();
function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280
return(rnd.seed/(233280.0))
}
function rand(number) {
return(Math.ceil(rnd()*number))
}