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

Marleen Berg
Marleen Berg
22,524 Points

I have a different solution, is this correct?

var minNumber = prompt("give your min number!");
var maxNumber = prompt("give your max number");

var diceRoll = Math.floor(Math.random() * parseInt(maxNumber) + parseInt(minNumber))+1;
alert(diceRoll);

I will have correct results, as far as I did test....

Adomas Domeika
Adomas Domeika
6,151 Points

yep, looks like your code is correct.

Sorry. Changing my opinion, why? Because if you enter your max number 20 an min number 15, then if random generates 18, you add the min number and the answer is 33. Sorry for the wrong answer.

2 Answers

I found a bug. I set minNumber to 5, and maxNumber to 11, and I got 15.

Hint on fixing bug: Sometimes, Math.random() * maxNumber can be close to maxNumber, because Math.random() can be close to 1, and if you add minNumber to that quantity, it may be above maxNumber.

Steven Parker
Steven Parker
231,275 Points

The math being applied here is not correct for creating a random number that will be within the two limits entered. The formula shown here will give you a number with a minimum one higher than the lower value, and a maximum of the sum of the two numbers entered.

The correct formula for a within-range random number with even distribution is:

random * range + minimum

where "range" is :point_right: maximum - minimum + 1