In creating a Proper Random Function, why is min, subtracted from the max in the code bracket?
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
In creating a Proper Random Function, why is min, subtracted from the max in the code bracket?
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
My suggestion for situations like this is to look at examples.
lets look for example at the case where min = 2
and max = 7
reading the expression from inside out,
Math.random()
will return some number between 0 to 1 (not including 1)
multiplying this with (max - min)
, in our case 5, will get number between 0 to 5 (not including 5). Applying Math.floor
to what we have, we get one of the numbers in the set {0, 1, 2, 3, 4}. Adding min
to it, we get one of the numbers in the set {2, 3, 4, 5, 6}
if you replace (max - min)
by max
you will get random number in the set {2, 3, 4, 5, 6, 7, 8}
try out few more examples until you get the idea
in general, the final result we want to get is a random whole number in the range [min, max)
so, we start with the range [0, 1)
lets assume that max is greater than min for the sake of simplicity.
multiplying it by (max - min) we get the range [0, max - min),
flooring it we get {0, 1, …, max - min - 1}
adding min to the last set, we get {min, min + 1, …, max - 1}
If I’m being honest… am still confused and don’t understand why the subtraction is happening. If you haven’t already, is it possible to explain it to me as you would to a 5 year old?
you want to get a random whole number between 2(inclusive) to 7(exclusive),
so, you start with 2 (this is the + min
part),
now you want to add some random number to 2 to get the result
now, think what random values will give you result between 2 to 7
start checking with 0, 1, etc…
Oh, I get your example… I think what confused me was when you described the second set of applying math.floor as {2,3,4,5,6} as opposed to {0,1,2,3,4,5,6}… so then… its not really necessary to have (max-min) then?
if you change (max - min)
to max
you get number between min
to max + min
and not a number between min
to max
I think I sorta get it. I don’t understand how learning functions can seem so easy and then putting them to practice can be so complex.
it’s always more hard to write things yourself
just keep learning,
if you feel the tasks are too hard, then reread the articles and possibly read the See also links
from my experience, after second and third reading you get to know the materials much better