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

GoldSpec Digital
GoldSpec Digital
4,185 Points

What is the user enters the first value as the higher number, and the second value as the lower number...

This only really works where the user enters the first number as the bottom number and the second number as the top number.

Lets say the user enters the first number as 50, and then the second number as 10, this would no longer make sense.

Is there a way, without restricting/limiting user input, that this could work nicely, regardless of which way round the number values are entered?

2 Answers

Chris Sukovich
Chris Sukovich
2,261 Points

I had the same thought when I was going through this exercise!

I used Math.min and Math.max and passed the two inputs – regardless of the order they were entered – to create new variables called min and max, then used those to determine the final random number. Check out my code below:

var first = parseInt( prompt("Pick a number"));

var second = parseInt( prompt("Pick another number"));

var min = Math.min(first, second);
var max = Math.max(first, second);

var random = Math.floor( (Math.random() * (max - min) + min));
console.log(random);

I solved it like that : var input = prompt("Please type a number 1 : "); var input2 = prompt("Please type a number 2 : ");

var topNumber = parseInt(input); var topNumber2 = parseInt(input2);

var randomNumber2 = Math.floor(Math.random() * topNumber) * Math.floor(Math.random() * topNumber2) + 1 var message2 = "<p> " + randomNumber2 + " is a number between " + topNumber + " and " + topNumber2 + " </p>" document.write(message2);