How to make Math.random not repeat same numbers

I have added an example for you. I think what you are interested in is the haveIt array, the !haveIt.includes(value) line and the recursive call.

let haveIt = [];

function generateUniqueRandom(maxNr) {
    //Generate random number
    let random = (Math.random() * maxNr).toFixed();

    //Coerce to number by boxing
    random = Number(random);

    if(!haveIt.includes(random)) {
        haveIt.push(random);
        return random;
    } else {
        if(haveIt.length < maxNr) {
          //Recursively generate number
         return  generateUniqueRandom(maxNr);
        } else {
          console.log('No more numbers available.')
          return false;
        }
    }
}


console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));

console.log(generateUniqueRandom(10));


console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));
console.log(generateUniqueRandom(10));


console.log('Unique random numbers:' ,haveIt);

Output :slight_smile:

1 Like