Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to random 10 numbers between 1 and 100 no dupes in javascript? [duplicate]

This has been asked dozens of times, but somehow, after reading many answers, I'm not convinced. I'm not cleared about the best way to do it, performance and code simplicity.

  1. Should I set the list [1.. 100] and keep picking random (it will run 10 times) from there to another array, avoiding searching for it every new random?

  2. Should I develop and run 10 times (at least) a random function to return a 1.. 100, checking if it is not a dupe and put it into an array?

  3. Some Javascript function that I'm missing?

Thanks

like image 527
noneJavaScript Avatar asked Jan 02 '23 23:01

noneJavaScript


1 Answers

You can use a while loop to generate random numbers with Math.random() and add the numbers to a Set which contains only unique values.

var randoms = new Set();
while(randoms.size<10){
  randoms.add(1 + Math.floor(Math.random() * 100));
}
console.log([...randoms.values()]);

You can also just use an Array and check if the generated random number already exists in it before pushing it to the Array.

var randoms = [];
while(randoms.length<10){
  var random = Math.ceil(1 + Math.floor(Math.random() * 100));
  if(randoms.indexOf(random)==-1){
    randoms.push(random);
  }
}
console.log(randoms);

For a more generic function, you can use this:

function generateRandoms(min, max, numOfRandoms, unique){
  /*min is the smallest possible generated number*/
  /*max is the largest possible generated number*/
  /*numOfRandoms is the number of random numbers to generate*/
  /*unique is a boolean specifying whether the generated random numbers need to be unique*/
    var getRandom = function(x, y){
      return Math.floor(Math.random() * (x - y + 1) + y);
    }
    var randoms = [];
    while(randoms.length<numOfRandoms){
      var random = getRandom(min, max);
      if(randoms.indexOf(random)==-1||!unique){
        randoms.push(random);
      }
    }
    return randoms;
}

function generateRandoms(min, max, numOfRandoms, unique){
    var getRandom = function(x, y){
      return Math.floor(Math.random() * (x - y + 1) + y);
    }
    var randoms = [];
    while(randoms.length<numOfRandoms){
      var random = getRandom(min, max);
      if(randoms.indexOf(random)==-1||!unique){
        randoms.push(random);
      }
    }
    return randoms;
}
console.log(generateRandoms(1, 100, 10, true));
like image 98
Unmitigated Avatar answered Jan 04 '23 12:01

Unmitigated