Generate Random Number without repetition Javascript

Asked

Viewed 1,174 times

1

So I want to generate this protocol, with random numbers and no repetition.

It’s functional, which means the code won’t repeat.

However, when clicking generate protocol, at the click, it was to generate, UNTIL finding a random number that does not repeat, however, if it does not find this number that repeats, it does not add anything in the list.

I’m having a hard time figuring it out, someone with some idea?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button type="button" class="botao"> Gerar Protocolo </button>
    <button type="button" class="botao2"> Postar Protocolos </button>
    <div class="type"> Protocolos: </div>
</body>

<style>
        .type {
            margin-top: 15px;
        }
</style>

<script> 

    function geraProtocolo () {
            var max = CheckMaxProtocol();
            var min = 1;

            return Math.floor(Math.random() * (max - min)) + 1;
        }

    function CheckMaxProtocol() {
            var max = 10;
            return max;
    }

    function verificaTotalVetor (vetor) {
        var verificaMaximo = CheckMaxProtocol();
            if (vetor.length >= verificaMaximo-1) {
                console.log("não é possível gerar novos protocolos.");
                return true;
            }
            else {
                return false;
            }
        }
    }

    var vetor = [];
    var auxiliaProtocolo = document.querySelector(".type");
    var limiteMaximo = CheckMaxProtocol();
    var botao = document.querySelector(".botao");
    botao.addEventListener("click",function() {
        var verificadorVetorCheio = verificaTotalVetor(vetor);

        if (verificadorVetorCheio == true) {
            return;
        }

        var resultado = geraProtocolo();
            vetor.push(resultado);


        for (var i = 0; i<vetor.length; i++) {
            for (var j = i+1; j<vetor.length; j++) {                    
                if (vetor[i] == vetor[j]) { 
                    vetor.pop(vetor[j]);
                    while (tamanhoVetor < vetor.length) {
                        console.log('he');
                        var result = geraProtocolo();
                        if (result != vetor[i]) {
                            vetor.push(result);
                        }                       
                    }
                }
            }   
        }
    });

    var botao2 = document.querySelector(".botao2");
    botao2.addEventListener("click",function(){
        if (vetor.length > 0) {
            var novoProtoco = document.createElement("p");
            auxiliaProtocolo.appendChild(novoProtoco);
            novoProtoco.innerHTML = "Protocolo: " + vetor;
        }
    });
</script>
No answers

Browser other questions tagged

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