Random numbers without repetition (JavaScript) [duplicate]

1

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

The problem is that the randomly generated numbers have repetition, do I want suggestions on how I can solve this problem so that the code is more reliable? Thanks for 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>
    
asked by anonymous 09.01.2018 / 14:17

1 answer

2

In order not to change the structure of your code a lot, 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 number drawn to the array of numbers, check if it is already there.

    
09.01.2018 / 14:31