Fill the array with random numbers without repetitions

I feel the expansion of madness. You need to get a unique array of N length from random numbers.

var arr = [],
    a = ~~(Math.random() * 42),
    i = 0;
while(b !== 42) {
    for(i=0; i<42; i+=1) {
        if(arr[i] !== a) {
            arr.push(a);
            a = ~~(Math.random() * 42);
            b+=1;
        }else{
            a = ~~(Math.random() * 42);
        }
    }
}

As a result, the arr array is filled with the same numbers in places. I ask for the help of the community, including showing your best implementations, which you can consider as such, if you wish.

Author: Дух сообщества, 2015-04-28

5 answers

Math.random returns independent random numbers, respectively, to get a random sequence of unique (that is, from all sides dependent) numbers, it will be extremely irrational to use your method.

To get the list you need, fill the array with consecutive numbers in the range you need, and then shuffle (sort in random order).

Here is Knuth's implementation of shuffle:

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

Well, next:

var arr = [];
for (var i = 0; i < 42; i++)
  arr.push(i);
shuffle(arr);
console.log(arr);

See How to randomize (shuffle) a JavaScript array?

 8
Author: Kyubey, 2017-05-23 12:39:00

Are you filling an array of N elements with N different numbers ranging from 0 to N?

But the result of such filling is called a permutation, so you need to generate a random permutation. Here is the third link for this query in Google:

Random permutation generation method, Fischer-Yates algorithm

 3
Author: Pavel Mayorov, 2015-04-28 05:50:20
var arr = []                         //записываем в этот массив рандомные числа
var max;                              // максимальная длина массива 
var rundomnumber;                     //случайное число

while (arr.length <= max) {

    rundomnumber = Math.floor(Math.random() * max); //создадим случайное число

    if (arr.indexOf(rundomnumber) == -1) {         // проверим есть оно  у нас или нет 

        arr.push(rundomnumber);         // записываем в массив т.к нету

    }
 }
 2
Author: Даниил, 2016-05-31 06:45:11

You can simply include each new number by checking for repetition in the array

var arr, max_number, i, unic;
arr = [];
max_number = 42;
while (arr.length < 42) {
  do {
    unic = true;
    a = Math.floor(Math.random() * 42);
    for (i = 0; i < arr.length; i++) {
      if (a == arr[i]) {
        // такое число уже было
        unic = false;
        break;
      }
    }
  } while (!unic) // повторить генерацию числа
  arr.push(a);
}
console.log(arr.join(";"))​;
 0
Author: vv-d, 2015-04-28 10:46:37
var size =  25, arr = [], pool = [];

for(var i = 0; i <= size; i++) {
    arr.push(i);
}

for(var i = 0; i <= size; i++) {
   var value =  arr.splice(Math.floor(Math.random() * ((size-i) - 1) + 1),1);
   pool.push(value.pop());
}
return pool;

The output - pool array consists of size random, non-repeating values

 0
Author: Dmitriy Kyrlovich, 2016-07-19 07:37:03