What condition can I develop to avoid duplicating values?

0

How to avoid duplicate numbers in this random generator?

var soma = 0
while (soma < 1000) {
    soma += parseInt(Math.random() * 100)
    document.write(soma + "<br>")
}

As you run, it arrives at a certain point that it brings with it incidences of values.

    
asked by anonymous 24.03.2017 / 12:25

3 answers

1

Suggestion:

Within while it generates a number and checks if it already exists inside the array that stores the numbers drawn.

If there is continue to while continue, if it does not exist, add it to the array and add it to soma .

var soma = 0;
var sorteados = [];
while (soma < 1000) {
  var nr = parseInt(Math.random() * 100, 10) + 1; // +1 para não aceitar "zero"
  if (sorteados.indexOf(nr) > -1) continue;
  soma += nr;
  sorteados.push(nr);
  console.log('Soma:', soma, 'Sorteado:', nr);
}
    
25.03.2017 / 11:56
3

You can use this code:

var soma = 0;
var numeros = [];
console.log('Soma: ' + soma);
while (soma < 1000) {
   numero = Math.random() * 100;
   if (numeros.indexOf(numero) < 0) {
       numeros.push(numero);
       soma += parseInt(numero);
       console.log('Soma: ' + soma);
   }
}
    
24.03.2017 / 12:42
1

It works by using indexOf as shown, but it would be more efficient (in terms of memory usage) to use a Hashtable , like this:

var soma = 0;
var sorteados = {};
while (soma < 1000) {
   var num = parseInt(Math.random() * 100);
   if (!sorteados.hasOwnProperty(num)) {
     sorteados[num] = true;
     soma += num;
     console.log(soma);
   }
}

Note: It is not recommended to use the document.write function as this rewrites all of your DOM, instead you should use javascript to retrieve elements from your DOM and add values or other elements to it.

    
25.03.2017 / 22:02