(HELP/LOST)Generate Random Whole Numbers within a Range

It’s the “distance” between the lowest and highest points of your range. It doesn’t make sense to explain it out of context, so I’ll explain the whole thing.

If min is 2 and max is 5, the “distance” from each other is 5 - 2 + 1 = 4. Then multiplying that by the result of Math.random() (a number from 0 up to, but not including 1), you’ll get a number from 0 up to, but not including 4.

Now you plug that number to the Math.floor function, which drops the decimal part of the number (if it’s positive), so you now have the integers 0, 1, 2 and 3.

At the end, you add the value of min, so you now have the integers 2, 3, 4 and 5, which are all of the integers in the range from 2 to 5.

If you removed the + 1 from (max - min + 1), you’ll only get the integers 2, 3 and 4, which is fine if you don’t want to include max in the numbers that you want to get.

35 Likes