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) Creating Reusable Code with Functions Random Number Challenge, Part II Solution

jay read
jay read
2,580 Points

Is there anything wrong doing it this way

Forget the fact that I haven't written the conditional statements yet. The way I have written the random number generator is different to the video, I would like to know if my way i still efficient. function getRandomNumber(val1, val2){

return Math.floor(Math.random() * val2 + val1); }

2 Answers

Steven Parker
Steven Parker
231,275 Points

It's a matter of operation, not efficiency. Your function is certainly efficient, but it does something different from the one in the video.

The video function takes two arguments, a lower limit and an upper limit, and generates a number between them (inclusive).

Your function takes two arguments also, but the first one is a lower limit and the second one is a range. It will generate a number somewhere within the range but offset by the limit.

So your version works, but in a different way, so it's not a solution to the challenge posed in the video.

It's wrong. For example, for any integer x, your getRandomNumber(x, 0) always evaluates to x. Not very random. Your getRandomNumber(-1, 0) never returns 0, and it sometimes should.

Steven Parker
Steven Parker
231,275 Points

The original formula could also be made to not be random with certain arguments. But both will generate a random number between 1 and 10 if called like: "getRandomNumber(1, 10)".

Steven Parker On the contrary, yes, it would. A correct implementation has an equal chance for getRandomNumber(-1, 0) to return -1 or 0. Not so with the one proposed here, since for integer x, getRandomNumber(x, 0) = Math.floor(Math.random() * 0 + x) = x.

Steven Parker
Steven Parker
231,275 Points

Yes, but as I said the first time, the arguments of the function shown above do something different from the one in the video.

I'm not contradicting your point, simply providing a definite example. Counterexamples are typically how generalizations are disproved, like the generalization that the proposed function is correct, i.e., always agrees with the function from the video. A counterexample proves the contrary: not all evaluations are correct.