Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading