0

this is my first question here.

I need to generate an array containing 16 random numbers and that's my solution:

var arr = [];
for (var i = 0; i < 16; i++) {
    arr.push(Math.floor(Math.random() * 100) + 1);
}

The problem is that in this way it is possible that there are repeated numbers. Is there someone who can help me? Thanks in advance.

Emanuel Rista
  • 55
  • 1
  • 6

2 Answers2

6

The shortest approach is to use a Set and check the wanted size of it.

let numbers = new Set,
    result;
    
while (numbers.size < 16) numbers.add(Math.floor(Math.random() * 100) + 1);


result = [...numbers];

console.log(...result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use a while loop

const MAX_NUMBER = 16;
const arr = [];

do {

  const randomNumber = Math.floor(Math.random() * 100) + 1
  
  // Push if the array does not contain it
  if (!arr.includes(randomNumber)) {
     arr.push(randomNumber);
  }

} while (arr.length < MAX_NUMBER);

console.log(arr)
Adam Azad
  • 11,171
  • 5
  • 29
  • 70