Trying to understand this logic


#1

Someone posted this code and a Codecademy Moderator appeared to agree that it works.
For me, it looks like any number 0-0.99 is going to give computerChoice = "rock".
Shouldn't the 0-0.5 and 0-0.75 be placed before 0-0.99.

For example, a value of 0.74 would give "rock".
In my updated code, a value of 0.74 would give "scissors".

Any thoughts?


OLD CODE:

var decideComputerChoice = function() {

    var computerChoice = Math.random();
    
    if (computerChoice <= 0.99) {
        computerChoice = "rock";
    } 
    else if (computerChoice <= 0.50) {
        computerChoice = "paper";
    } 
    else if (computerChoice <= 0.75) {
        computerChoice = "scissors";
    }
    else {
        computerChoice = "rope";
    }
    return computerChoice;
}

NEW CODE:

var decideComputerChoice = function() {

    var computerChoice = Math.random();
    
    if (computerChoice <= 0.50) {
        computerChoice = "paper";
    } 
    else if (computerChoice <= 0.75) {
        computerChoice = "scissors";
    } 
    else if (computerChoice <= 0.99) {
        computerChoice = "rock";
    }
    else {
        computerChoice = "rope";
    }
    return computerChoice;
}


#2

I have seen that in a few post but I think it is incorrect as i always get rock. I have come up with this piece of code but I have not had a response. Not sure if you have to use the and (&&) operator.
example:

var userChoice = prompt('Do you choose rock, paper or scissors?');
var computerChoice = Math.random();

if (computerChoice <= 0.33) {
console.log("rock");
}
else if (computerChoice >= 0.34 && computerChoice <= 0.66) {
console.log("paper");
}
else {
console.log("scissors");
}

console.log(computerChoice);


#3

For your code you can use

<= 0.33

and then....

<=0.67

So if the math.random number is 0.3 it would give rock. But 0.4 would fail the first statement but still be picked up by the second statement as 0.4 is <= 0.67. That will make your code clearer for sure


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.