+ 1

How to fill an array with 4 random, non repeating numbers?

here is my work so far: const randNum=()=>Math.floor(Math.random()*4) const tempArr=[randNum()] for(let i=0;i<=4;i++){ let num=randNum(); while(!tempArr.includes(num)){ tempArr.push(num); } } console.log(tempArr)

9th Dec 2020, 6:38 PM
Logomonic Learning
Logomonic Learning - avatar
2 Respostas
+ 1
The loop you should be set to stop iterating once the tempArr length is four, meaning it should keep iterating however many times is necessary to get an array filled with four non-repeating numbers. I suggest using a while loop to do this. const randNum=()=>Math.floor(Math.random()*4) // while loop based on the length of tempArr const tempArr=[randNum()] while(tempArr.length < 4){ let num = randNum(); !tempArr.includes(num) && tempArr.push(num) } console.log(tempArr) // recursion based on size of set object const set = new Set(); const recurse = () => set.size < 4 && recurse(set.add(randNum())) recurse() console.log([...set])
9th Dec 2020, 8:20 PM
ODLNT
ODLNT - avatar
+ 1
ODLNT I love how you used && in the loop
10th Dec 2020, 10:29 PM
Ali Kh
Ali Kh - avatar