Reputation: 15
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'
Upvotes: 1
Views: 57
Reputation: 530
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 );
}
}
Upvotes: 0
Reputation: 44087
Just add another condition to your if
statement:
if (arr.indexOf(random_number) == -1 && random_number != answer) {
arr.push(random_number);
}
Upvotes: 1