3

I want to generate an array with a random number that each number is different. Could someone help me to solve this? Thanks.

        var array = [];
        for(var i = 0;i < 5; i++){
            var a = Math.floor(Math.random() * 5);
            array.push(a);
        }
        console.log(array);
Leonard
  • 79
  • 1
  • 8
  • 4
    Make an array of unique numbers: `[0,1,2,3,4]` - then shuffle that array using your algorithm of choice (Fisher-Yates Shuffle recommended). This will ensure the results are unique. – Niet the Dark Absol Jun 27 '20 at 14:35
  • The logic you are applying will work just instead of multiplying with 5 , multiply with a multiple of 10 eg. 100000. Number of zeroes equal to number of digits you want for random number. – Adesh Kumar Jun 27 '20 at 14:35
  • 1
    Here for example result [0, 0, 4, 2, 0] . I want every number in this array is different such as [1,4,2,0,3] – Leonard Jun 27 '20 at 14:37
  • `set = new Set(); while (set.size < 5) set.add(Math.floor(Math.random() * 5));` – MikeM Jun 27 '20 at 15:13

3 Answers3

2

var array = [];
for (var i = 0; i < 10; i++) {
  var a = Math.floor(Math.random() * 10);
  while (array.indexOf(a) !== -1) {
    a = Math.floor(Math.random() * 10);
  }
  array.push(a);
}
console.log(array);
Nithish
  • 5,393
  • 2
  • 9
  • 24
1

with this implementation you will be sure you are not going to add more than one time an existing number inside var array.

var array = [];

function randomNumber(array) {
    var a = Math.floor(Math.random() * 5);
    var found = array.filter(el => el == a);
    if(found.length) return randomNumber(array);
    return a;
}

for(var i = 0; i < 5; i++){
    array.push(randomNumber(array));
}

console.log(array);
Luke
  • 29
  • 7
1

Math.random() returns a number a floating point number between 0 & 1. So multiplying with a 5 and then doing Math.floor can result a number between 0 & 4. Hence you array may contain duplicate number

var array = [];
for (var i = 0; i < 5; i++) {
  var a = parseInt(Math.random() * i * 100, 10);
  array.push(a);
}
console.log(array);
brk
  • 48,835
  • 10
  • 56
  • 78