Draw numbers without repeating in javascript

Asked

Viewed 5,803 times

4

I need to draw 16 numbers and store them in an array, but there can be no repeat numbers. Follow the code.

var numero = [];

function numero_aleatorio () {
	
		for(i=0;i<16;i++) {
		
		numero.push(Math.floor((Math.random() * 16) + 1)); 	

	}
}

numero_aleatorio();

  • 3

    that question already has an answer. https://answall.com/questions/10282/n%C3%Bamero-aleat%C3%B3rio-sem-repeti%C3%A7%C3%A3o? Rq=1

  • I tried using that function [https://answall.com/questions/10282/n%C3%Bamero-aleat%C3%B3rio-sem-repeti%C3%A7%C3%A3o? Rq=1], but it wasn’t working

  • 1

    Hello Diego, I voted to close because even the answer of Sérgio not being the one who seeks the following answer, of Bacco, answers exactly what you need https://pt.stackoverflowcom/a/10284/3635, it is always nice look hereafter of the answer accepted, other answers even if not accepted may solve the problem ;D

3 answers

6


Just check if the number is in the array before adding it. You need to change the for by a while, since it is not possible to know exactly how many iterations it will take to generate 16 different numbers:

var numeros = [];

function numero_aleatorio() {
    while (numeros.length < 16) {
        var aleatorio = Math.floor(Math.random() * 100);

        if (numeros.indexOf(aleatorio) == -1)
            numeros.push(aleatorio);
    }
}

numero_aleatorio();

Note that Math.floor(Math.random() * 100) generates a random number between 0 and 99.

  • It was really worth @rodorgas ! I could only explain this part of the code? if (numeros.indexOf(aleatorio) == -1)&#xA; numeros.push(aleatorio);

  • "The index() method returns the first index where the element can be found in the array, returns -1 if it is not present." -MDN. Therefore, if numeros.indexOf result in -1 for the number we have just generated, it is not present in the array and should be added.

  • Ah blz! Got it! Thank you very much! :)

  • It’s nois! You could wear the most elegant if (!numero.includes(aleatorio)), but like the includes entered in ES7 does not work in IE.

  • 1

    In fact, Math.floor(Math.random() * 100) generates a number between 0 (not 10) and 99.

  • Oops... You’re right @Wtrmute. I updated the answer, thanks.

Show 1 more comment

2

You can insert the numbers from 1 to 16 within a array and use the method sort of array randomly sorting with the function Math.random());

function _sortear(quantidade, maximo) {
  var numeros = [];

  console.time('Sorteando');

  // Preenche um array com os números de 1 ao maximo
  for (var numero = 1; numero <= maximo;  numero++) {
    numeros.push(numero);
  }
  
  numeros.sort(function randomizar(a, b) {
    return Math.random() * 2 - 1; // Ordena randomicamente
  });

  console.timeEnd('Sorteando');
  
  return numeros.splice(0, quantidade);
}

console.log(_sortear(16, 100).join(','));

Note that I created the parameters quantidade and maximo. To quantidade defines how many numbers should be returned and the maximo sets the maximum random number value.

At the end of the function I use the method splice to pick up the n first positions of the array resultant.

-2

Follow in simple example friend,

public class NumerosAleatrorios{
public static void main(String[] args){
    int numero;
    int[] num = new int[6];
    Random r = new Random();
    for(int i=0; i<num.length; i++){
         numero = r.nextInt(60) + 1;
         for(int j=0; j<num.length; j++){
               if(numero == num[j] && j != i){
                     numero = r.nextInt(60) + 1;
               }else{
                    num[i] = numero;
               }
         }
    }
    //Apresentar na tela o resultado
    for(int i=0; i<num.length; i++){
         System.out.print(num[i]+"  ");
    }
  }
}
  • 2

    You haven’t explained what’s right in your code or wrong in the AP code. It also has the fact that you answered Java but required Javascript in the question

  • So I needed the code in javascript. But thanks for the reply Felipe :)

Browser other questions tagged

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