How can I draw an X number without repeating it in JS?

Asked

Viewed 42 times

0

let user = require(`readline-sync`)

let loteria = {
    totalNumeros: "",
    intervalo: "",
    numeros1: "",
    numeros: [],
    numeroexcluido: "",
    sortear: function () {
        this.totalNumeros = user.questionInt("Informe quantos numeros deseja sortear: ")
        this.intervalo = user.questionInt("Informe qual o numero maximo: ")

        for (let i = 0; i < this.totalNumeros; i++) {
            this.numeros[i] = Math.floor(Math.random() * this.totalNumeros + 1)
                    
        }

        console.log(this.numeros);

    }

}

draw lottery.()

This is the code so far, I just wanted to perfect it but I’m cracking my head and I can’t.

2 answers

1

Fala Miguel!

  • You will make a loop, with the total numbers you will want.
  • You will create an array to add the non-repeated numbers randomly.
  • First you will generate a random number within the loop.
  • Second you will check if this number exists in the array, if it does not exist, you can make a . push in that array with the random number. If this happens (there is no number in the array and you put it in there), you would have to decrease the total number to get it out of the loop!

Follow the code below:

let total = 20;
const numbers = [];
const maxValue = 100;

while (total > 0) {
  const number = Math.floor(Math.random() * maxValue);
  if (!numbers.includes(number)) {
    numbers.push(number)
    total -= 1
  }
}

console.log(numbers)

1

I suggested creating an array with all possible numbers to be drawn. Then remove it from that array and add it to a new one with the numbers drawn. When using length to array to get the random index and knowing that the drawn number is removed, there is no chance of ever leaving repeated numbers.

It would be something like:

const totalNumeros = +window.prompt('Informe quantos numeros deseja sortear:');
const intervalo = +window.prompt('Informe qual o numero maximo:');
const intervaloArray = [...Array(intervalo).keys()];
const numeros = [];

for (let i = 0; i < totalNumeros; i++) {
  const index = Math.floor(Math.random() * intervaloArray.length);
  numeros.push(+intervaloArray.splice(index, 1) + 1);
}

console.log(numeros);

Browser other questions tagged

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