Problems with Generate Radom Whole numbers within a range

Tell us what’s happening:
Dear All,
Good afternoons,
I have a question about the following function:
I do understand the usage of Math.floor and Math.random but i don´t understand this part specifically:

(ourMax - ourMin + 1 ) + ourMin;
i know the ranges are ourMax and ourMin but what does the + 1 means ? and why we add a + ourMin?

I will appreciate and thank you all so much all the advises and orientation you can provide,
thank you all in advance for your kind reply,
Regards,
Ivonne

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 these values to test your function
var myRandom = randomRange(5, 15);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36.

Challenge: Generate Random Whole Numbers within a Range

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range

1 Like

ourMax - ourMin + 1 gives the length of the range. for example if you want a random number between 5 and 7, you can get any between 5, 6, and 7, so 3 numbers: 7 - 5 + 1 is 3.
Math.random() gives a number between 0 (included) and 1 (excluded)
so Math.floor(Math.random() * 3) will give 0, 1 or 2. to get a number in the range you need to add 5 (ourMin)

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.

Dear @ieahleen,
Good afternoons,

I thank you so much for the orientation
and kind reponse, :slight_smile:
Now i feel i understand more this chapter, thank you for your time and help,
Have a Blessed day,
Kind regards,
Ivonne

The reason we add 1 to the difference between ourMin and ourMax is because Math.random() generates a number from 0 (inclusive) and 1 (exclusive). In other words, Math.random() might generate 0, but it will never generate 1. If we don’t add 1 to ourMax - ourMin, then we will never get a number greater than or equal to ourMax and when we put that result in Math.floor() then the largest number that the function can generate is ourMax -1.

1 Like

Dear @ArielLeslie,
Good afternoons,
:slight_smile: thank you for the kidness and your time in explaining me
the usage of the value 1, i appreciate it!!!
Have a Blessed day,
Kind regards and i thank you again,
Ivonne

I’m glad I could help. Happy coding!

1 Like