Answers for "math.random non repeat same number"

0

math.random non repeat same number

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);
Posted by: Guest on February-02-2021

Code answers related to "math.random non repeat same number"

Code answers related to "Javascript"

Browse Popular Code Answers by Language