Chris Chris - 3 months ago 9
Javascript Question

Random numbers for array, but not the same | JavaScript

I'm trying to create an array of numbers. The array should look like the following:

[1, 2, 1]
or
[2, 1, 2]


I don't want the same number again after it's already been chosen.

So I don't want
[1, 1, 2]
or
[2, 2, 1]


I have the following code:

var chosenHosts = [];

for (var i = 0; i < match.match_games; ++i) {
var num = 1 + Math.floor(Math.random() * 2);

chosenHosts.push(num);
}

console.log(chosenHosts);


This code pushes the same number twice. Does anyone have an idea on how to achieve as described above?

P.S. Sorry for the confusing title, I didn't know how else to describe it.

Answer

Something like this will work

var chosenHosts = [1 + Math.floor(Math.random() * 2)];

for (var i = 1; i <  match.match_games; i++) {
     var num = chosenHosts[i - 1] == 1 ? 2 : 1; 
     chosenHosts.push(num);
}

console.log(chosenHosts);