在javascript中1到100之间随机10个数字的最佳方法没有欺骗? [英] Best approach to random 10 numbers between 1 and 100 no dupes in javascript?

查看:90
本文介绍了在javascript中1到100之间随机10个数字的最佳方法没有欺骗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已被问了好几次,但不知怎的,在读了很多答案之后,我不相信。我不清楚最好的方法,性能和代码简单。

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. 我应该设置列表[1从那里到另一个阵列继续随机选择(它将运行10次),避免每次随机搜索它?

  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?

我应该开发吗?并运行10次(至少)一个随机函数返回1 ... 100,检查它是不是一个欺骗并把它放入一个数组?

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?

我缺少一些Javascript函数?

Some Javascript function that I'm missing?

谢谢

推荐答案

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

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

这篇关于在javascript中1到100之间随机10个数字的最佳方法没有欺骗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆