Random Numbers without repetition.(Javascript)

Asked

Viewed 953 times

1

Good morning, I created a small lottery game, where is generated 06 numbers between 0-20, the user informs his guess of 06 numbers and the system returns how many numbers were hit and which numbers were hit.

The problem is that the randomly generated numbers have repetition, I want suggestions on how to solve this problem so the code is more reliable? I appreciate any help.

<script type="text/javascript">     
    jogo = [];
    sorteio = [];
    acertos = [];

    i = 1;

    while(i<=6){
        jogo.push(Math.round(Math.random()*20));
        sorteio.push(parseInt(prompt("Informe a "+i+"ª Dezena!")));
        i++;        
    };
    for (var i = 0; i<jogo.length; i++) {
        if(sorteio.indexOf(jogo[i])>-1){
            acertos.push(jogo[i]);
        }           
    };

    alert("Sorteio: "+jogo+"\nAposta: "+sorteio+"\nVocê acertou " + acertos.length + " números: "+ acertos);

    console.log(jogo);
    console.log(sorteio);
    console.log(acertos);
    console.log("Você acertou " + acertos.length + " números: ", acertos);

</script>
  • Store the numbers already drawn in a hashmap. Each new number, if you draw one that has already come out, draw again.

1 answer

2


To not change the structure of your code too much, basically you will change the line jogo.push(Math.round(Math.random()*20)); to use this structure:

while(i<=6){
    var novoNum = -1;
    do {
        novoNum = Math.round(Math.random()*20);
    } while (jogo.indexOf(novoNum) >= 0);
    jogo.push(novoNum);

    //segue o código
};

The idea is that before adding the drawn number to the number array, check if it is already there.

  • 1

    Thank you @rLinhares , I implemented the changes, after 10 attempts there was no repetition.... Thanks.

Browser other questions tagged

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