JavaScript random function

by on January 31, 2006

Q: How do I create a JavaScript random function that does not return two consecutive identical results?

A: Random functions are always interesting topics but this one just caught my eye because the user wanted a random function that did not repeat two numbers in a row. This means 1,2,1,5 is acceptable but 1,1,2,5 is not because there are two returns in a row that have the same value.

Thankfully JavaScript makes this a very easy task for us. We will create a global called randNum and set it equal to 0 and then we will create a function called randNoDups that will take an argument of maxNum (which will be 1 larger than the largest number possible).

The key is to look at our current random number and compare it to our last random number. If they are equal to each other then we need to generate another random number. Here is the code!

<script language=”JavaScript”>
var randNum = 0;
function randNoDups(maxNum)
{
tmpRand = randNum;
while (tmpRand == randNum) {
tmpRand = Math.round(Math.random()*maxNum);
}
randNum = tmpRand;
return tmpRand;
}
</script>