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

sebbe12
sebbe12
4,015 Points

var a = Math.floor(Math.random() * (number1-number2+1))+number2;

How does this one work. Let's say number1 is 15 and number2 is 10.

This is my logic:

First it calculate (number1-number2+1))+number2; (15-10+1)+10 =16.

Then it takes 16 * Math.random() = Lets say Math.random is 0.05 then it should be 0.8 and result in 0.

How come everything land between 10-15.

1 Answer

Wikus van der Westhuizen
PLUS
Wikus van der Westhuizen
Courses Plus Student 4,335 Points

This is a basic math problem. You need to remember the order of computation: BODMAS

var a = Math.floor(Math.random() * (number1-number2+1))+number2;

Your oder of computation will be:

var z = (number1-number2+1);
var y = Math.random() * z;
var x = Math.floor(y);
var a = x + number2;

So using your example the computation will be:

var number1 = 15;
var number2 = 10;
var rndNumber = 0.05; // Substituting Math.random() with a fixed number
Math.floor(rndNumber * (number1-number2+1))+number2;
Math.floor(0.05 * (15-10+1))+10;
Math.floor(0.05 * (6))+10;
Math.floor(0.3)+10;
0 + 10;
10