Javascript: Generate Random Integer Between Min and Max
A newbies guide to generating a Random Number in JavaScript.
Random numbers in JavaScript are easy to generate using the built-in function Math.random(). Math.Random produces a random floating point number between 0 and 1, such as 0.75634 or 0.26349.
In practice we often need to generate a random number between an upper (max) and lower (min) limit. We can do this by
var x = (Math.random() * max) + min
If we are only interested in integers, we can further refine this by using Math.floor() to remove the decimal places:
var x = Math.floor((Math.random() * max) + min))
We can put this code in a function so it will be easier to reuse:
function randomInteger(min, max) { // returns integer between min and max return Math.floor((Math.random() * max) + min); }
Testing our code
No matter how simple our code looks we should still test that it works properly. There’s several ways to do this and I’ll test it here by writing a test routine that will generate 10,000 random numbers between 1 and 10, and display the percentage of each occurrence. Theoretically that should be 10% each.
We should also test at the boundary conditions: there should be no number generated below 1 or higher than 10, so I’m also going to count the number of occurrences of 0 and 11.
// create an array to hold our results var num = new Array(12); // initialise each element to zero for (var count = 0; count < 12; count++) { num[count] = 0; } // generate 10,000 random numbers between 1 and 10 // and increment the counter array for (var i = 0; i < 100000; i++) { var index = randomInteger(1, 10); num[index] += 1; } // write the results out to the console. // Note: You usually get the console by pressing F12 in your Browser for (var count = 0; count < 12; count++) { console.log(count + ": " + num[count] + " ["+ num[count]/1000 +"%]"); }
When you run this you should get the results quite quickly in the Console Window of your Browser, such as:
0: 0 [0%] 1: 9941 [9.941%] 2: 10040 [10.04%] 3: 9973 [9.973%] 4: 10009 [10.009%] 5: 9936 [9.936%] 6: 9951 [9.951%] 7: 10072 [10.072%] 8: 10073 [10.073%] 9: 9989 [9.989%] 10: 10016 [10.016%] 11: 0 [0%]
The results will be slightly different every time we run this (it is random after all) but the result is about what we would expect.