最好的方法来随机1到100之间的10个数字在javascript中没有重复项?

时间:2018-08-17 15:04:44

标签: javascript random

已经问过几十遍了,但是不知何故,在阅读了许多答案之后,我不敢相信。关于最佳方法,性能和代码简单性,我还不清楚。

  1. 我应该设置列表[1 .. 100]并继续从那里选择随机(它将运行10次)到另一个数组,以避免每次搜索新的随机数吗?

  2. 我是否应该开发并运行10次(至少)一个随机函数以返回1 .. 100,检查它是否不是dupe并将其放入数组?

  3. 我缺少一些Javascript函数?

谢谢

5 个答案:

答案 0 :(得分:4)

您可以使用while循环使用Math.random()生成随机数,并将数字添加到仅包含唯一值的Set中。

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

您也可以只使用一个数组,然后在将生成的随机数推送到数组之前检查其中是否已经存在。

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);

要获得更通用的功能,可以使用此功能:

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));

答案 1 :(得分:3)

此技术创建N1个数字(总范围)并对其进行混洗,然后选择顶部的N2个数字(我们实际需要多少个),我们将使用Fisher-Yates混洗。

const n1 = 100;
const n2 = 10;

let pool = [...Array(n1).keys()];

var result = [];

while (result.length < n2) {
   let index = Math.floor(Math.random() * pool.length);
   result = result.concat(pool.splice(index, 1));       
}

console.log(result);

答案 2 :(得分:2)

gulp.task('styles', ['clean-styles'], function () {
 return gulp.src('content/styles/main.scss')
    //Instead of crash the task, notify and keep running
    .pipe($.plumber({
        errorHandler: onErrorCSS
    }))
    .pipe($.sourcemaps.init())
    .pipe($.sass(sassOptions))
    .pipe($.autoprefixer(afOptions))
    .pipe($.sourcemaps.write('.'))
    .pipe(gulp.dest('content'))
    //Inject changes (no reload) of css.
    .pipe(browserSync.stream({ match: "**/*.css" }))
    .pipe($.notify({
        title: 'CSS',
        subtitle: 'CSS',
        message: '✓',
        sound: "Pop"
    }));
});

答案 3 :(得分:0)

#2是最有效的。

var nums = []
while(nums.length < 10) {
  var n = Math.round(Math.random()*100);
  if (!nums.includes(n)) nums.push(n);
}
console.log(nums);

您还可以在较新的浏览器中使用Set,这比手动检查存在性要快一点:

var nums = new Set();
while(nums.size < 10) {
  var n = Math.round(Math.random()*100);
  nums.add(n);
}
console.log([...nums.values()]);

答案 4 :(得分:-1)

此函数将betweenStartbetweenEnd的所有数字相加,在randomRuns循环中将它们随机化,并返回包含amount项的列表:

function randomNumbersBetweenXAndY(betweenStart, betweenEnd, amount, randomRuns) {
    if (betweenStart === void 0) { betweenStart = 0; }
    if (betweenEnd === void 0) { betweenEnd = 100; }
    if (amount === void 0) { amount = 10; }
    if (randomRuns === void 0) { randomRuns = 1; }
    //Verify parameters
    var maxPossibleCandidates = Math.abs(betweenStart - betweenEnd) + 1;
    if (amount > maxPossibleCandidates) {
        console.warn("You cannot get more unique numbers between " + betweenStart + " and " + betweenStart + " than " + maxPossibleCandidates + ". " + amount + " is too many!");
        amount = maxPossibleCandidates;
    }
    //array to return
    var list = [];
    //fill array
    for (var index = betweenStart; index <= betweenEnd; index++) {
        list.push(index);
    }
    //Randomize
    while (randomRuns--) {
        for (var index = 0; index < list.length; index++) {
            var randomIndex = Math.floor(Math.random() * list.length);
            var tmp = list[index];
            list[index] = list[randomIndex];
            list[randomIndex] = tmp;
        }
    }
    //Return data
    return list.slice(0, amount);
}
//TEST
console.log(randomNumbersBetweenXAndY(1, 100, 10));