lundi 17 août 2020

Generating an array with 3 unique numbers

I'm trying to create an array with three unique random numbers between 1 and 14. I've found similar questions on Stackoverflow and used the code to help me create my existing code.

It works well most of the time, but occasionaly it will create an array with two of the same numbers. Here is the offending code:

function noDuplicates (sideRandom) {
  sideArray.splice(sideRandom, 1);
  let sideRandom2 = Math.floor(Math.random() * 14) + 1;
  sideArray.push(sideRandom2);
  console.log("I've had to add " + sideRandom2)
}

function sortNumbers(array) {
  array.sort(function(a, b) {
    return a - b;
  });
}

document.getElementById("randomiser").addEventListener("click", function () {

  for (let i = 0; sideArray.length <3; i++) {
    let sideRandom = Math.floor(Math.random() * 14) + 1;

    console.log(sideRandom);
    if (sideArray.includes(sideRandom) === false) {
      sideArray.push(sideRandom);
    } else {
    noDuplicates(sideRandom);    
    };
  }    
  console.log(sideArray);
});

I suspect the issue is that sometimes the noDuplicates function generates the same random number as sideRandom, but I can't see a way around it. can you help?




Aucun commentaire:

Enregistrer un commentaire