What condition can I develop to avoid duplicating values?

Asked

Viewed 101 times

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 it goes running, it arrives at a certain moment that it brings with it incidences of values.

  • You have to resize the values that have already been "drawn" somewhere. How many single numbers do you want? between 0 and 1000?

  • @Sergio Então Sergio, would leave only a single number between 0 and 1000. For example: 0 1 2 4 7 9 ... and avoid duplication of values 0 1 1 2 4 7 9 9 ...

3 answers

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);
   }
}

  • But it still keeps repeating. You could adjust your solution in order to improve?

1


Suggestion:

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

If it exists does continue to the while continue, if it does not exist, add it to the array and add it to the 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);
}

1

Works using indexOf as shown, but it would be more efficient (in terms of memory usage) to use a Hashtable, thus:

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 function document.write because this rewrites all your DOM, instead you should use javascript to retrieve elements from your DOM and add values or other elements to it.

  • I agree with you, with the new changes of Ecmascript. But to illustrate the (s) example(s) I still find both the alert() how much document.write(). But it’s worth your place!

Browser other questions tagged

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