Random numbers 1 to 3 without repetition

Asked

Viewed 344 times

2

I am developing a web project related to a test system A/B, and I need a function that generates random numbers from 1 to 3 without repeating those that have already been generated.

function getRandom(max){ return Math.floor(Math.random() * max + 1); } 
  • What have you programmed ? Have some code ?

  • Function getRandom(max)' Return Math.floor(Math.Random() * max + 1); }

1 answer

3

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

To not repeat it is enough to store the ones that have already been generated in an array and insert a conditional one. 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);
   }
  }
}
  • How would he look with the array , I did not draw ?

  • https://jsfiddle.net/c586veqo/

  • 2

    Seems to work +1. tip can post your reply from duplicate...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.