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 trialBianca Power
8,094 PointsQuestion about the maths
I'm wondering why we can't just do what I've done... clearly it's wrong otherwise there wouldn't have been a more complicated version as the "solution" :P
My workspace: https://w.trhou.se/5ee0hav2fo
2 Answers
Damien Watson
27,419 PointsHi Bianca,
I'm not sure what the video shows, but you are very close to the solution. Using:
//EXT: collect 2 numbers, and generate a random number between the two
var usrNum1 = 4;
var usrNum2 = 10;
var randNum = Math.floor(Math.random() * usrNum2) + usrNum1;
The key is 'between the two'... a random between 4 and 10 for example.
Math.random() * usrNum2
will return decimal numbers between 0.0 and 9.9ish. You are then using Math.floor
which means it returns numbers 0 to 9. Then adding usrNum1 to it, gives a number between 4 and 13 (not 10).
Math.random() * (usrNum2 + 1 - usrNum1)
would return between 0.0 and 6.9 -> 0 to 6 with Math.floor(). Then adding the num1 would make this from 4 to 10.
usrNum1 = 4;
userNum2 = 10;
var randNum = Math.floor(Math.random() * (usrNum2+1-usrNum1)) + usrNum1;
I think this does the trick. Cheers.
Ethan M
10,637 PointsDefinitely a great method Bianca! I did something a lot different that Dave's solution. Everyone has a different way of doing things.
I did something very similar to your code but took a lot of trial and error for a beginner like me. I have had experience with JavaScript but I still suck at it haha. As well with C# but that's what programming is. Trial and error.
Good luck on your learning career and I am sure you will even find cooler ways on making the random number challenge!
Ethan M
10,637 PointsAlso, Dave goes into incredible detail with his solutions for the learning purpose. It's so students really understand the purpose of the code.
Bianca Power
8,094 PointsBianca Power
8,094 PointsGreat, that makes sense! Thanks so much!