-2

Can someone help me? I would like to make a simple code where dom generates a random number from 0-14 and adds it to the ran array and it will only stop once all numbers from 0-14 are inside the array.

function random () {
let ran = []
let dom = Math.floor(Math.random() * 15)
while (a != a.length(15)) {
   a.push(b)
   return a
 }
}

console.log(random)
Benri
  • 1
  • 1
    You will be better off with a different approach: generate an array with consecutive numbers from 0 to 14 and shuffle it (google for Fisher-Yates or Durstenfeld). – Carsten Massmann Oct 01 '21 at 06:26
  • You need to generate a new number inside the loop. You must *not* `return` inside the loop, since that ends it. You'll probably want to test whether the number is already in the array, not the array's length? Finally, this may be a lot easier by simply *shuffling* an array containing numbers from 0-14…?! – deceze Oct 01 '21 at 06:26
  • 1
    I might have overstepped by closing this as a duplicate of shuffling an array, but in all respects, that's the better solution. Just generating random values until you happen to find the missing piece is wildly inefficient. – Robby Cornelissen Oct 01 '21 at 06:29

1 Answers1

0

Logic.

  • random function keeps on pushing random mnumbers from 0-14 to the ran array
  • checkAllNumberpresent creates a number array from 0 - 14 using Array.from(Array(15).keys())
  • This function accept the input array and check whther any numbers from the input array is missing in the numberArray
  • If all are present, the function returns false and this stops the while loop execution.

Working Fiddle

function checkAllNumberpresent(arr) {
  const numberArray = Array.from(Array(15).keys());
  const missingNodes = numberArray.filter(item => arr.indexOf(item) === -1);
  return missingNodes.length == 0;
}
function random() {
  const ran = [];
  while (!checkAllNumberpresent(ran)) {
    let dom = Math.floor(Math.random() * 15);
    ran.push(dom)
  }
  return ran
}

console.log(random())
Nitheesh
  • 19,238
  • 3
  • 22
  • 49