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 Solution

Walter Young
PLUS
Walter Young
Courses Plus Student 3,523 Points

How do I create a random number that doesn't include the two given values?

I took things one step further and used Math methods so the order of upper/lower shouldn't matter:

function ranNumRange(x,y) { return Math.floor(Math.random() * (Math.abs(x - y) + 1) + Math.min(x,y)); }

However, if I put, say, (5,3) or (3,5) the program can also return the two given values. Values with larger differences seem to be fine. What is the most elegant (minimal code) way to fix this?

1 Answer

Steven Parker
Steven Parker
229,771 Points

You can revise the formula to exclude the limit values from the range instead of including them:

Math.floor(Math.random() * (Math.abs(x - y) - 1)) + Math.min(x,y) + 1