Welcome to the Treehouse Community
Looking to learn something new?
Felipe Belinassi1,567 Points
Help with my solutions
This my two solutions to the challenge (one user input and two user inputs).
var userNumber = prompt("Hey! Type a number"); userNumber = parseInt(userNumber); var number = Math.floor(Math.random() * userNumber) + 1; alert("You picked " + userNumber + ". Your random number from 1 to " + userNumber + " is " + number);
var minNumber = parseInt(prompt("Type a number!")); var maxNumber = parseInt(prompt("Now type a higher number!")); var random = Math.floor(Math.random() * maxNumber) + minNumber; alert("You picked " + minNumber + " and " + maxNumber + ". Your random number from " + minNumber + " to " + maxNumber + " is " + random);
I don't know if my solution to one input is right. But i'm sure my solution for two inputs is incorrect (sometimes the random number is bigger than the user maxNumber input). Could someone help me?
Alexandra Wakefield1,866 Points
The mishap in your Two Input is with the line
var random = Math.floor(Math.random() * maxNumber) + minNumber;
Instead of using the minNumber as a base, which could be anything, you are using it as an additive to whatever random number is created.
Example: Let's say you entered 2 as your minNumber, 6 as your maxNumber and Math.random generates 0.9. This creates the equation:
(0.9 * 6) + 2 = 7.4
Math.floor rounds this down to 7. As you can see, this is happening because there is no actual base and you're instead using the minNumber as a replacement for the +1, which is there to raise the (Math.random() * maxNumber) to 1 if Math.random decides to equal 0.
Well then, what can you do? Doug gives a great solution, I just moved the + 1 into the maxNumber and minNumber's parenthesis to ensure that if the number generated by Math.random is 0 the minNumber added to it will not be +1 higher than the our wanted minimum:
var random = Math.floor(Math.random() * (maxNumber - minNumber + 1)) + minNumber;
What This Solution Does
- has minNumber act as a base
- + 1 is there in case Math.random equals 0 as well as to help reach the maxNumber
- the + minNumber ensures that the maxNumber can be reached while a number under minNumber cannot
Example: Let's use the same numbers as before.
(0.9 * (6 - 2 + 1)) + 2 = 6.9 = 6
If our lowest is 0:
(0 * (6 - 0 + 1)) + 0 = 0