Generate Random Whole Numbers within a Range - help

Generate Random Whole Numbers within a Range - help
0.0 0


Tell us what’s happening:
I did not understand this at all

Your code so far

// Example
function ourRandomRange(ourMin, ourMax) {

  return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;

ourRandomRange(1, 9);

// Only change code below this line.

function randomRange(myMin, myMax) {

  return (Math.floor(Math.random() * (myMax - myMin + 1) + myMin)); // Change this line


// Change these values to test your function
var myRandom = randomRange(5, 15);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0.

Link to the challenge:


Your code works so I guess you don’t understand how it works.

Math.random returns a floating point (decimal) number such that 0 <= num < 1. We want a number that has a range that is a difference of min and max. If min and max are 5 and 20, then we want a range of 15. But wait, we actually want 16, because there are 16 possible numbers between 5 and 20 if we include both 5 and 15 (hence the +1). So, we generate our number, multiply it by our range, then add our min (to boost it back up to start at 5) and floor it, round it down.

Here is a pen to show you what is happening. If you run it and open up the browser console (crtrl-shft-j) it will show you how many of each number it gets in the random trials. You can monkey with the numbers to see how it works.


Thanks, that was well explained