Explanation Of Code: Dealing With Min And Max - Javascript
Solution 1:
But I don't get why im subtracting the max from the min and adding + 1 and then +myMin.
First remember that Math.random()
returns a value in the range of [0, 1)
.
Lets start from the end:
+ myMin
is done to ensure that the result is larger or equal tomyMin
. Lets assumeMath.random()
returns0
. ThenMath.floor(...)
returns0
. If we didn't+ myMin
, return result would be0
instead ofmyMin
.+ 1
is done to get random values that includemyMax
. Remember thatMath.random()
never returns1
, only values close to1
. I.e. theMath.floor(Math.random() * myMax)
can never bemyMax
unless we add1
.myMax - myMin
is done because we do+ myMin
above. We have to account for increasing the result bymyMin
.Lets assume
Math.random()
returns0.5
and our range is100 - 120
. Without- myMin
, we would getMath.floor(0.5 * 120) + 100 = 60 + 100 = 160
That's clearly larger than
120
. If we include- myMin
:Math.floor(0.5 * (120 - 100)) + 100 = (0.5 * 20) + 100 = 110
we get
110
which is exactly in the middle of our range (which makes sense intuitively since we get0.5
as a random value).
Solution 2:
Math.random returns float number between 0 to 1. For example if you take 1 to 10 range. Then Math.random will return minimum 0 and maximum 1 then you multiply it with 10-1=9. And you get 0 to 9. But when you add the minimum it will be increased to 1 to 10.
Solution 3:
Correction - it's not creating a range, it is generating a random Integer number between a given range of numbers ( minimum and maximum number).
E.g. (5, 15) = (min, max)
Will result in a number that is in between this range.
Code explanation :
Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;
Let's assume both max and min are = 15
So the above will look like:
Math.floor(Math.random() * (15 - 15 + 1)) + 15;
Which is equal to = 15, since 0 <= Math.random() * (1) < 1 so the floor of this is 0.
If you don't add that 1, it will not be valid for this corner case.
You add minimum to make sure the value remains between min and max.
Post a Comment for "Explanation Of Code: Dealing With Min And Max - Javascript"