dimanche 22 août 2021

How do I generate a 4-digit number with no duplicates

I wanna generate a 4-digit number with no duplicates, here are the functions that generate a random number with 4-digits. I'm curious if there is a JS method that can do that for me, or do I have to loop through the elements, or even do a while loop until it generates a number with no duplicates (since it's only 4 digits, it is small anyway)..

function genRandomNumber(range = 10) {
  return Math.floor(Math.random() * range);
}

function HiddenNumber(digit = 4) {
    const number = Array.from(
  {
    length: digit
  }, () => genRandomNumber()).join("");
  console.log(number);
  return Number(number);
}



Aucun commentaire:

Enregistrer un commentaire