1

I've generated an array of three random numbers unique from each other (no duplicates). Now I also want to make sure that all three of the random numbers are also unique from the variable "answer".

var answer = 4;

//Generating the three random numbers
var arr = [];

while (arr.length < 3) {
    var random_number = Math.floor(Math.random() * 9) + 1;
    if (arr.indexOf(random_number) == -1) { 
        arr.push( random_number );
    }
}

I cant seem to make it so that each of the three numbers is not equal to the variable 'answer'

1

2 Answers 2

1

Just add another condition to your if statement:

if (arr.indexOf(random_number) == -1 && random_number != answer) {
  arr.push(random_number);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, don't know why I didn't try that. I did try "||" though lol
0

add && condition also

var answer = 4;

//Generating the three random numbers
var arr = [];

while (arr.length < 3) {
    var random_number = Math.floor(Math.random() * 9) + 1;
    if (arr.indexOf(random_number) == -1 && random_number != answer) { 
        arr.push( random_number );
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.