Basic JavaScript - Generate Random Whole Numbers within a Range

Tell us what’s happening:
Describe your issue in detail here.
I have finished the challenge but I still don’t know why should we have plus > myMin at the end

Your code so far

function randomRange(myMin, myMax) {
  // Only change code below this line
  return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
  // Only change code above this line
}
console.log(randomRange(3,8))

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Generate Random Whole Numbers within a Range

Link to the challenge:

This part makes sure that the minimum random number will be myMin.

Simple way to see that is to replace the

With 0

(Math.random() can return zero to less than 1 values so when it does, the + myMin; will be very important to make sure the minimum is always equal or above myMin)

After you test with 0, try testing with 0.1 and 0.2 etc in place of the Math.random() call.

can you explain about this hole equation please
cauz I am still confused a bit

This is just some simple maths to get the multiplier that will move and spread the randomly generated number to a higher range.

If I have the number 0.1 returned by Math.random, then how do I make this number bigger respective of the given range?
(If the myMin for eg is 10 and the myMax is 20?)

Ask yourself how would you map the 0.1 to a value inside the 10 to 20 range?

0.1 * (20-10+1) + 10
0.1 * (11) + 10
1.1 + 10
11.1

Essentially we turn the number 0.1 into 11.1 and floor that down to 11 which is within the required 10 to 20 range.

Just try to plug-in some numbers into the equation to see how it works.

If the range was 10 to 100 for eg

0.1 * (100-10+1)+ 10
0.1 * (91) + 10
9.1 + 10
19.1
Which gets floored down to 19

Thus a random 0.1 gets mapped to 19 within the given range.

1 Like

Thanks for your help on the this report today, I couldn’t have done it without you

1 Like

I am all set to go now :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.