Generate Random Whole Numbers within a Range
Instead of generating a random number between zero and a given number like we did before, we can generate a random number that falls within a range of two specific numbers.
To do this, we’ll define a minimum number min and a maximum number max.
Here’s the formula we’ll use. Take a moment to read it and try to understand what this code is doing:
Math.floor(Math.random() * (max - min + 1)) + min
Instructions
Create a function called randomRange that takes a range myMin and myMax and returns a random number that’s greater than or equal to myMin, and is less than or equal to myMax, inclusive.
// Example
return 0; // Change this line
}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) {
// Example
return 0; // Change this line
}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) {
// Change these values to test your function
var myRandom = randomRange(5, 15);
// Change these values to test your function
var myRandom = randomRange(5, 15);
It’s the “distance” between the lowest and highest points of your range. It doesn’t make sense to explain it out of context, so I’ll explain the whole thing.
If min is 2 and max is 5, the “distance” from each other is 5 - 2 + 1 = 4. Then multiplying that by the result of Math.random() (a number from 0 up to, but not including 1), you’ll get a number from 0 up to, but not including 4.
Now you plug that number to the Math.floor function, which drops the decimal part of the number (if it’s positive), so you now have the integers 0, 1, 2 and 3.
At the end, you add the value of min, so you now have the integers 2, 3, 4 and 5, which are all of the integers in the range from 2 to 5.
If you removed the + 1 from (max - min + 1), you’ll only get the integers 2, 3 and 4, which is fine if you don’t want to include max in the numbers that you want to get.
That was an awesome explanation, thank you @kevcomedia. It bent my brain trying to understand the concept of ‘distance’ but it finally sank in!
Thanks again!
This is the best explanation I’ve seen so far—thank you. I’ve seen many “just do it like this,” but nobody so far has said, “this is how the math works.” You’ve helped my weary brain.