Populate vector and check if current position value is equal to previous

Asked

Viewed 80 times

0

btnInnerText(btns[0],sorteio());
var bool = true;
for(var i=1;i<btns.length;i++){
    do{
        btnInnerText(btns[i],sorteio());
        for(var j=0;j<btns.length;j++){
            if(getValorBTN(i)==getValorBTN(j))
                bool=false;             
            else
                bool=true;

        }
    }while(bool==true)

}

for(var i=0;i<btns.length;i++){
    console.log("Posição = "+i+" - Valor = "+getValorBTN(i));
}

The problem is that it always generates some repeated numbers. And what I want is that Randomize random numbers without repeating any value in the vector

inserir a descrição da imagem aqui

The draw function is to draw a number between 1 and 10 and the function getValorBTN is to take the values of the HTML boats

function getValorBTN(posicaoBTN){
    var valor=parseInt(document.getElementById(btns[posicaoBTN]).textContent);
    return valor;
}

Another thing I don’t quite understand is that if I put the condition while(bool==false) gets into loop infinity. I’m certainly confusing things, but I think it was to repeat when bool=false and leave when it’s the other way around.

  • If getValorBTN is a function, why are you using brackets to access? getValorBTN[i]==getValorBTN[j]

  • Another thing, Voce explained the problem but didn’t explain what he wants to do. I didn’t say what the point of all this is. Seems like you want to generate a vector with random numbers without repetition.

  • Fixed, but now it’s in infinite loop

  • That’s exactly what I want, I updated the post

  • As I said, after the correction, it is in an infinite loop. I put two different console.log to check if I entered the if or Else, and I was checking. But even so it did not leave the loop, only putting the break in Else. And even with the break, still repeats some numbers in the vector

  • What this condition means getValorBTN(i)==getValorBTN(j)? What is the intention behind it?

  • Check at all positions for an equal value. In this case, as i starts in 1, the second for(var j=0;j<btns.length;j++) will scroll through all the HTML buttons, take their value (getValorBTN) and check. I put inside the.. while to redo the draw without repeating

Show 2 more comments

1 answer

2


i want Randomize random numbers without repeating any value in the vector

First, let’s create a function that returns a random number within a specific range.

function obterNumeroAleatorio(minimo, maximo) {
  return minimo + Math.floor(Math.random() * (maximo - minimo + 1));
}

Now, let’s create a function that accumulates N random numbers within a specific range.

function gerarNumerosSemRepeticao(quantidadeNumeros, minimo, maximo) {
  const numerosSemRepeticao = new Set();

  while (numerosSemRepeticao.size < quantidadeNumeros) {
    const numeroAleatorio = obterNumeroAleatorio(minimo, maximo);
    numerosSemRepeticao.add(numeroAleatorio);
  }

  return [...numerosSemRepeticao];
}

Therefore, to generate 10 random numbers between 1 and 100, just call

const numeros = gerarNumerosSemRepeticao(10, 1, 100);
console.log(numeros);
  • In case you don’t know what it is Set, click here.
  • In case you don’t know what it is [...x], click here.

If you want to use arrays only, you just make a loop for comparing the number drawn with each of the numbers already selected.

function gerarNumerosSemRepeticao(quantidadeNumeros, minimo, maximo) {
  const numerosSelecionados = [];

  while (numerosSelecionados.length < quantidadeNumeros) {
    const numeroSorteado = obterNumeroAleatorio(minimo, maximo);
    let encontrouIgual = false;

    for (const numero of numerosSelecionados) {
      if (numero === numeroSorteado) {
        encontrouIgual = true;
        break;
      }
    }

    if (!encontrouIgual) {
      numerosSelecionados.push(numeroSorteado);
    }
  }

  return numerosSelecionados;
}

But keep in mind that this greatly worsens the execution time of the function. Using Set she is O(n), using array she becomes O(n^2). If you don’t know what that means, click here.


Just out of curiosity, know that you can also create an array of sequential numbers and mix them randomly. The final result will be the same (whereas the random number range comprises all numbers in the vector).

To mix the elements of a vector use Knuth’s shuffle algorithm (if you don’t know what it is, click here).

function misturarElementos(vetor) {
  function inverter(i, j) {
    const temp = vetor[i];
    vetor[i] = vetor[j];
    vetor[j] = temp;
  }

  for (let i = vetor.length - 1; i; i--) {
    let j = obterNumeroAleatorio(0, i);
    inverter(i, j);
  }
}

Example of use:

const numeros = [];

// Preencher o vetor com números sequenciais
for (let i = 1; i <= 10; i++) {
  numeros.push(i);
}

// Usar o Knuth shuffle para embaralhar os elementos no vetor
misturarElementos(numeros);

// Agora os elementos parecem aleatórios!
console.log(numeros);

This algorithm is O(n).

  • It really works out of your method. I wanted to know, is if there is a way to fill whatever the vector and go checking if there are equal values in it, using loop of repetitions. I want to know for purposes of knowledge, after all my logic was confused, I wanted to correct this, only the ready answer does not make sense to my learning... Grateful!

  • 1

    @Henrique I edited the answer to show the logic using only arrays, but note that the algorithm becomes much less efficient.

  • 1

    @Henrique I added another way to do what you want. A very different approach.

  • Very interesting, in these times that a CC college is needed, especially for me that I have a vision with libraries/ ready functions. I only use these means to produce faster, but what I really like is to learn what happens behind to the maximum. Thanks for the answers

Browser other questions tagged

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