Random numbers from 1 to 3 without repetition [duplicate]

2

I'm developing a Web project related to an A / B test system, and I need a function that generates random numbers from 1 to 3 strong> without repeating the ones that have already been generated.

function getRandom(max){ return Math.floor(Math.random() * max + 1); } 
    
asked by anonymous 03.12.2016 / 12:52

1 answer

3
Math.floor(Math.random() * 4);

Not to repeat you just store the ones that have already been generated in an array and insert a conditional. Something like:

 var numSorteados = [];
var numSorteios = 10;
var numAtual = 0;
for (i = 0; i <= numSorteios; i++){
  numAtual = Math.floor(Math.random() * 4);
  if(numAtual != 0){
    if(numSorteados.indexOf(numAtual) ==-1){
     numSorteados.push(numAtual);
     window.alert("O número sorteado foi "+numAtual);
   }
  }
}
    
03.12.2016 / 13:23