Need help --Generate Random Whole Numbers within a Range

can’t understand the formula
Math.floor(Math.random() * (max - min + 1)) + min

Math.floor is used to round down the numbers. Math.random() will give a number between 0 and 1, but never 1.
min and max are sort of the ceiling and floor parameters passed in to the math.random function.

Math.floor = rounding
Math.random = generates the random num
max - min + 1 = all the numbers in the range, ex 8 - 1 + 1 (all numbers between 1 and 7 ). This means you could get 1, but never 8. In my example, the code would be:

Math.floor(Math.random()* 8 - 1 + 1) + 1;    // gives a random number between 
                                            // 1 and 7 each time you run this.

Hope this helps!

is there any other way ?

As far as I know (and I’m definitely not an expert) that’s the only way. The only way it could be changed is breaking it up into steps. If you’re having trouble with it, maybe it’ll help to break it down further into steps:

  • Math.random() = random number between 0 and 1 (inclucing 0, excluding 1)
  • (max - min + 1) = the number of possible numbers you want (you add one so that it will include max, like if you count the numbers from 5 to 10 there are 6 which is 10-5+1
  • Math.random() * (max-min+1) = random numbers between 0 and the number of whole numbers you want (in the 5-10 example, it gives you random numbers between 0 and 6, including 0 excluding 6)
  • Math.floor(the above) drops all numbers after the initial number, leaving whole numbers from 0 to the difference between your numbers (with 5 & 10, this gives 0, 1, 2, 3, 4, and 5 in equal proportion)
  • Finally, you add the miniumum to this to move the range from 0 to (max-min) up to min to max

I hope that helps combined with counterculture’s answer.


Sure there’s another way - right a function that takes a min and a max and returns your random number. The inside of that function will still have that ugly formula, but it will at least be hidden.