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) Working With Numbers The Random Challenge

My solution

Hi all,

this is the first time I post in forum. Would like to get familiar with it and share my code also. Thanks!

//Random number from 1 to the given number
function ranForYou() {
    var choice;
    do {
        choice = prompt("This machine will create a random integer Number between 1 and the number you choose. So please choose a number first. It should be a NUMBER and bigger than 1.");
    } while(isNaN(parseInt(choice)) || parseInt(choice) <= 1);
    //used Math.ceil() instead of Math.floor(...) + 1
    var randomNumber = Math.ceil(Math.random() * parseInt(choice));
    alert("The random number is " + randomNumber);
}

//Random number between the 2 given numbers
function randomForYou() {
    var choice;
    do {
        choice = prompt("This machine will create a random integer Number between the 2 numbers you choose. So please choose both numbers first. Make sure there are TWO NUMBERS. Separate them with A SPACE please");
        var numbers = choice.split(" ");
    } while(isNaN(numbers[0]) || isNaN(numbers[1]) || numbers[0] === '' || numbers[1] === '' || numbers.length > 2);
    //Math.ceil() keeps the result of "2 3" always 3, so changed to Math.round()
    var randomNumberBase = Math.round(Math.random() * (parseInt(numbers[1]) - parseInt(numbers[0])));
    alert("The random number is " + (randomNumberBase + parseInt(numbers[0])));
}

1 Answer

Vittorio Somaschini
Vittorio Somaschini
33,371 Points

Hi Sunny.

Welcome to the forum, your first post is well formatted and code is properly pasted! So, that was a good start indeed!

I have quickly tested your 2 pieces of code and they do their job fine, so it looks like a good job!

Hope to see you again and soon on the forums with some other code! ;)

Vittorio

Many thanks for your kind reply and test, Vittorio. :D

Couldn't wait to learn and enjoy more. xD