mercredi 23 décembre 2020

What's the best way to pull random numbers from source array of numbers untill there is no unique values left in the source array?

I need to create a makeRandom function that accepts a range of numbers as an array, where the first number is the beginning of the range, the second is the end including this number in the range. The result of this function should be a function, and the call returns a random number from the range. The numbers returned must be unique. If I run out of unique numbers, have to return null.

It should work like this :

const getRandom = makeRandom([1, 5]);
getRandom() === 3
getRandom() === 4
getRandom() === 5
getRandom() === 2
getRandom() === 1
getRandom() === null
getRandom() === null

So I tried :

function makeRandom(numbers) {
  return () => {
    let randNumber = Math.floor(Math.random() * numbers.length);

    for (let i = 0; i < numbers.length; i++) {
      randNumber += numbers[i];

      if (randNumber === numbers[i]) {
        return true;
      }

      if (randNumber === numers[i].length) {
        return true;
      }
    }

    if (!numbers) {
      return null;
    }
  };
}

But it's not working. So what's the best way to do this?




Aucun commentaire:

Enregistrer un commentaire