You’re right. We multiply by the size of the range to scale the random number. We then add the minimum value to “shift” our scaled random number into the range.
Math.random() gives us a random number between 0 and 1.
But we don’t want a random decimal; we want a random number. We can get that by multiplying our Math.random() result by the size of the range. For example, if we want a random number between 0 and 10, we need to multiply by 10. A result of 0.4 would become 4. If we want random numbers from 7 to 11, that is 5 possible numbers (7, 8, 9, 10, 11).
This is where we get Math.random() * (max - min + 1)
We don’t want decimal numbers though, we want whole numbers. Math.floor() just chops off the decimal. 3.14159 becomes 3.
That’s where we get Math.floor(Math.random() * (max - min + 1)).
Now we’re getting a number from 0 to whatever our range size was. If we wanted a number from 7 to 11, it’s a random number from 0 to 5. To make that be a number from 7 to 11, we just need to add 7 to whatever number we got. 7 is our minimum value.
This leads us to Math.floor(Math.random() * (max - min + 1)) + min
I know it’s been a while, but here I am & I thought I’d throw in my 2 cents just in case it helps someone else. Combined with ArielLeslie’s description above it helped me.
I don’t think verbally, so this is how I had to work it out:
What we’re trying to achieve with the above is to gather the range of numbers between myMax and myMin, to be later multiplied by a decimal between 0 and 1(non-inclusive).
Imagine this;
if myMax = 10, myMin = 5
per your formula, 10 - 5 = 5
However,
the numbers between 5 and 10 inclusive are as follows: 5, 6, 7, 8 ,9 ,10
there are a total of 6 numbers.
There is no array involved here.
The +1 is needed if we have an inclusive range. Remember that Math.random() is non-inclusive of 1. If our min is 2 and our max is 5, we want to include 2, 3, 4, 5. That’s four numbers. But 5-2 is 3. That’s why we add 1.
Sorry once again this is a little old, but I just wanted to add to this (maybe others can benefit from different wording):
This was how I would explain why add 1 (similar to the explanation by @ArielLeslie) :
When the range is first found, this value is an exclusive range (doesn’t include the min and max ). However, due to the way Math.random() works, this becomes a half-inclusive range, where it includes the min but not the max (refer to previous exercise). Thus, to make this an inclusive range, you add 1 to it to compensate for the missing spot of the max .
Just replying to say I’m doing this in 2020 and did not understand this at all until I saw your explanation. Your explanation is still helping people out, 2.5 years later!! How awesome is that? Thank you!