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 trialHamza Saleemi
4,257 PointsWill it still work if upper is smaller than lower? and if so why?
if upper is smaller than lower then wouldn't it produce a negative value which can cause an error or a bug because the functionResult might not be in the required range. To compensate for this I used the following code:
function randomNum(first, second) {
if (first > second){
var upper = first;
var lower = second;
} else {
var upper = second;
var lower = first;
}
var functionResult = Math.floor(Math.random() * (upper - lower + 1)) + lower;
return functionResult;
}
randomNum(10,20);
console.log(randomNum(10,20));
Now my solution seems to work as well, but what I can't understand is how does his solution work?
1 Answer
Steven Parker
231,271 PointsThe original solution only works correctly if the numbers are entered in the proper order.
With a small number of tests, it might seem that it works either way,. But if you collected extensive statistics on it, you would discover that when the order is reversed, the random number generated will have a more limited range than intended.
Your mod generates in the proper range no matter what order the numbers are given. Good job.
Hamza Saleemi
4,257 PointsHamza Saleemi
4,257 PointsThanks! I kept scratching my brain for an hour trying to figure out how his method was working, but your explanation makes sense!