-2

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.

Chris
  • 1,574
  • 4
  • 16
  • 49

2 Answers2

4

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);
baao
  • 71,625
  • 17
  • 143
  • 203
  • this will only work if the random numbers are between 1 or 2 – depperm Aug 30 '16 at 18:59
  • True - like OP asked for @depperm – baao Aug 30 '16 at 19:00
  • @baao That's almost what I need! This outputs 4 numbers. I only need 3. Do you have any idea on how to achieve that? – Chris Aug 30 '16 at 19:00
  • So your match.match_games always holds 3 entries? @Chris – baao Aug 30 '16 at 19:02
  • @baao It varies between 1 or 3 – Chris Aug 30 '16 at 19:02
  • @Chris change `for` condition to `i < match.match_games-1;` – depperm Aug 30 '16 at 19:03
  • Ok, changed it @Chris - now it does exactly what you want – baao Aug 30 '16 at 19:03
  • @Chris, same approach, different code: `for(var chosenHosts = [], num = 1 + Math.floor(Math.random()*2); chosenHosts.length < match.match_games; num = 1+(num&1)) chosenHosts.push(num);` – Thomas Aug 30 '16 at 19:19
  • @Thomas have a look here http://stackoverflow.com/questions/183201/should-a-developer-aim-for-readability-or-performance-first. Micro optimization over readability is never a good idea! – baao Aug 30 '16 at 19:23
  • Another possible way of streamlining that strikes me as more readable: `var chosenHosts = Math.random() < 0.5 ? [1, 2, 1] ? [2, 1, 2]; chosenHosts = chosenHosts.slice(0, match.match_games);` Depending on how the array is consumed, you might not even need to bother with the second line. – DLH Aug 31 '16 at 02:43
0

You can check the last element in the array and continue creating a random number until it's different.

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

for (var i = 0; i < match.match_games; i++) {
  var r = 1 + Math.floor(Math.random() * 2);
  while (chosenHosts[i] == r)
    r = 1 + Math.floor(Math.random() * 2);
  chosenHosts.push(r);
}

console.log(chosenHosts);
depperm
  • 10,606
  • 4
  • 43
  • 67