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

Chauncey Garrett
Chauncey Garrett
3,977 Points

Solution that doesn’t require the user to distinguish between high/low values.

Here’s my solution which allows the user to input any two numbers, regardless of magnitude:

var userNumber1 = parseInt(prompt("Enter any integer greater than 1"));
var userNumber2 = parseInt(prompt("Enter a different integer greater than 1"));
var randomNumber = Math.floor(Math.random() * (Math.abs(userNumber1 - userNumber2) + 1)) + Math.min(userNumber1, userNumber2);
alert(randomNumber);

It uses Math.abs() which provides the absolute value of the two numbers entered and Math.min() which returns the lower of the two numbers. I found these on MDN.

Couple of tips:

  • Remember that Math.random() provides a number in the range [0,1) -> that is, 0 to .999 repeating
  • Adding the +1 makes the larger inclusive [min,max]; removing it excludes the max value [min,max)
  • Math.floor() returns an integer; without it, there’d be a random (non-integer) number returned

Hope that helps!

__ROLLER__ Angel
__ROLLER__ Angel
25,606 Points

Very creative solution using the MDN and trying out a sensible method to create a solution.

that is fascinating. I think this part of the course is directed toward people like me that are clueless. These problems are devised just to teach. I am certain there are many more practical solutions to many more practical problems. But for people like me this is just part of he process.