Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Working With Numbers The Random Challenge

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

2nd part of the challenge

i dont get 2nd part of the challenge. like how does it work to create a random number between top and bottom number and the why do we have to add 1 in it again? and then you also added bottom number to the result.....i thought we add 1 to make 1 inclusive in the range, like in the 1st part of the challenge. played video over n over again to hold the grip of it, but just getting confused i guess, any simple solution?

3 Answers

Steven Parker
Steven Parker
215,972 Points

The formula to convert a random number from 0 (inclusive) to 1 (exclusive) into an inclusive range is:
floor( random * range ) + minimum         where "range" is:     maximum - minimum + 1

The reason you add one to the difference between the values is to make the range wide enough to cover both the limits. Then after multiplying (and using the floor function to get integer values) the range is correct but the lowest possible value is still 0. So you add the minimum back in to shift the range up between (and including) the limits.

if the minimum value of the range will be 1, you can simplify the formula to:   floor( random * maximum ) + 1

Thank you for your explanation. That's helpful.

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

Ok I understand abit more now but still little difficult for me to grasp all that ! Is it normal for me to feel at this stage ? I feel like I can remember it now n might forget later on again, I dnt wana Jst get this challenge right n move on I wana fully understand all how it works. Do I suggest I shud do this move on to next? As m still in process of learning the whole programming!

Steven Parker
Steven Parker
215,972 Points

Don't worry about remembering formulas, you can always look them up when you need them. You've got plenty to do working on the basic concepts of programming.

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

Yeh true. Thanks a lot for ur help!