Noah
Noah

Reputation: 15

Generating random numbers unique from another variable

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

Answers (2)

Prabhat Kumar
Prabhat Kumar

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

Jack Bashford
Jack Bashford

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

Related Questions