Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Working With Numbers The Random Challenge Solution

Jean Brea
Jean Brea
3,877 Points

Did I do this right?

I have no Idea If I pulled this of, please tell me.

Here is my code: var givenNumber1 = prompt("Please enter a number"); var solidNum = parseInt(givenNumber1); var givenNumber2 = prompt("Please enter a second number"); var solidNum = parseInt(givenNumber2); var randNum = Math.floor(Math.random() * givenNumber1) + 1 + Math.floor(Math.random() * givenNumber2) - 1; document.write(randNum);

3 Answers

I think it's fine using the two variables, though think a bit more about the names you choose. For example consider something like inputMin and inputMax instead of givenNumber1 and givenNumber2. In a more complex program, you may forget which variable contains the value you're after.

Also, I think this is a test of using documentation too. In this case this page actually contains the following example:

// Returns a random integer between min (included) and max (included)
// Using Math.round() will give you a non-uniform distribution!
function getRandomIntInclusive(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

which is exactly what we're after. For my solution I simply took the code out of the function and adapted it to the variables I'd already defined.

Timothy Wright-Bodine
Timothy Wright-Bodine
9,670 Points

No, there are a few problems. First, instead of getting the numbers with one variable and using parseInt() to assign to a second variable, you can get each parsed int in a single step: var givenNumber1 = parseInt(prompt("Please enter a top number")); var givenNumber2= parseInt(prompt("Please enter a bottom number"));

Second, to get a random number between those two numbers, you first have to find the difference between the top and bottom numbers (subtract bottom from top), multiply that difference plus one by Math.random(), and call Math.floor() on that. This will get you a random number that is within the difference between the two given numbers. Then you just add the bottom number to that and you have a random number between the top and bottom numbers.

var randNum = Math.floor(Math.random() * (givenNumber1 - givenNumber2 + 1)) + givenNumber2;

Jean Brea
Jean Brea
3,877 Points

Thank you all for the help!