Sorting numbers without repeating in javascript [duplicate]

4

I need to draw 16 numbers and store them in an array, but there can be no repeated 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();
    
asked by anonymous 21.06.2017 / 19:44

3 answers

6

Just check if the number is in the array before adding it. It is necessary to change for by while , since it is not possible to know for sure how many iterations will be necessary 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.

    
21.06.2017 / 19:54
2

You can enter numbers from 1 to 16 within a array and use the sort method of array by randomly sorting 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 . The quantidade defines how many numbers are to be returned and maximo sets the maximum value of the random numbers.

At the end of the function I use the splice method to get the n first positions of the resulting array .

    
22.06.2017 / 01:10
-2

Follow the 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]+"  ");
    }
  }
}
    
21.06.2017 / 19:48