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);
4
  • 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. Commented Jun 27, 2020 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. Commented Jun 27, 2020 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] Commented Jun 27, 2020 at 14:37
  • set = new Set(); while (set.size < 5) set.add(Math.floor(Math.random() * 5)); Commented Jun 27, 2020 at 15:13

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.