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 trialVic Mercier
3,276 Pointsmath.floor(math.random()*random1-random2+1)+random1;
I don't know why we add +random1 at the end of the syntax.
1 Answer
Steven Parker
231,271 PointsThat's the way the formula for a random pick works.
The formula is: "(random * range) + minimum
" where range is: "maximum - minimum + 1
".
But that would mean your numbers are out of order, plus you need parentheses to override the operator precedence. So your code should probably be:
math.floor(math.random() * (random2 - random1 + 1)) + random1;
Nadav Reis
5,561 PointsNadav Reis
5,561 PointsI believe that without the +random1 at the end, the number would be outside of the range.
Imagine is your numbers were 75 and 100. The difference is 25.
You would get something like .82929299 * 25 + 1
The result is not between 75 and 100. If you add 75 back in (ie, add random1), your number will be between 75 and 100.