Skip to content
Advertisement

How to choose randomly unique number when the button is clicked

I am trying to choose random unique numbers everytime when I click button. For this my function is:

const chooseNumber = () => {
    var r = Math.floor(Math.random() * 75) + 1;
    console.log(r)
    while(selectedNumbers.indexOf(r) === -1) {
      selectedNumbers.push(r);
    }
    console.log(selectedNumbers);
  };

But the problem is if the random number is already on my list, I need to click the button again to generate new number and it goes until it find the number which is not on the list. But I want to generate number which is not on the list directly so I dont need to click the button everytime. Thanks for you helps.

Advertisement

Answer

You are in a right track, except the while loop should be for random number generator, not pushing number into an array:

const selectedNumbers = [];
const chooseNumber = () => {
    let r;
    do
    {
      r = Math.floor(Math.random() * 75) + 1;
    }
    while(selectedNumbers.indexOf(r) > -1)
    selectedNumbers.push(r);
    console.log(r, "["+selectedNumbers+"]");
  };
<button onclick="chooseNumber()">Generate</button>

Note, that this might eventually lead to a freeze, since there is no fail safe check if array is full, so to battle that we should also check length of the array:

const selectedNumbers = [];
const maxNumber = 75;
const chooseNumber = () => {
  let r;
  do
  {
    r = ~~(Math.random() * maxNumber) + 1;
  }
  while(selectedNumbers.indexOf(r) > -1 && selectedNumbers.length < maxNumber)
  if (selectedNumbers.length < maxNumber)
    selectedNumbers.push(r);
  else
    console.log("array is full");

  console.log(r, "["+selectedNumbers+"]");
};


for(let i = 0; i < 76; i++)
{
  chooseNumber();
}
<button onclick="chooseNumber()">Generate</button>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement