-1

I need help with my code. I want to get 10 random numbers every time it rolls and it can't have duplicated, this is my code:

for(let j = 1; j <= 21; j++) {
    const number = (Math.floor((Math.random() * j) + 1))
    const genNumber = array.indexOf(number);
    if (genNumber === -1) {
        array.push(number);
    }
}

I have no idea how I can get exactly 10 numbers every time, anyway it can be written with js or jquery it doesnt metter for me. Hope I can get help here.

Gihan
  • 3,144
  • 2
  • 9
  • 36
Mariusz
  • 149
  • 2
  • 8

2 Answers2

0

I don't really understand what your code is intended to do, but to get exactly 10 unique random numbers I'd use a Set and loop until it's filled. I have no idea why you loop 21 times for 10 items though...

let s = new Set();
while (s.size < 10) {
  s.add((Math.floor(Math.random() * 21 /* ??? */) + 1));
}

console.log([...s]);
baao
  • 71,625
  • 17
  • 143
  • 203
0

You're almost there, but instead of using a for loop, use a while loop that continues as long as there are less than 10 things in the array:

const array = [];
const j = 21; // Pick numbers between 1 and 21 (inclusive)

while (array.length < 10) {
    const number = (Math.floor((Math.random() * j) + 1))
    const genNumber = array.indexOf(number);
    if (genNumber === -1) {
        array.push(number);
    }
}

console.log(array);
CRice
  • 29,968
  • 4
  • 57
  • 70