【问题标题】:How to get a certain number of unique random numbers in a certain range?如何在一定范围内获得一定数量的唯一随机数?
【发布时间】:2019-10-07 16:00:55
【问题描述】:

我有一个函数,它接受用户输入来告诉它要输出多少个随机数,以及生成随机数的范围(比如 1-90)。问题是它会给出重复的数字,但我只想要唯一的数字。有谁知道我可以如何更改代码来实现这一点?

function random() {
    let randomNums = [];

// Get how many random numbers to output
    let numBox = document.querySelector('.numBox').value;

// Get the highest number range should go to (ex. 1-70)
    let highestNumber = document.querySelector('.highestNumber').value;

// Loop to generate random numbers and push to randomNums array
    for (let i = 0; i < numBox; i++) {
        let num = Math.floor(Math.random() * highestNumber) + 1;
        randomNums.push(` ${num}`)  
    }     

// Sort numbers from lowest to highest
    randomNums.sort(function(a, b) {return a - b;});

// Output numbers
    document.querySelector('.randomOutput').innerHTML = randomNums;
}

【问题讨论】:

  • 您可以跟踪以前包含的值,Unique number 可以这样做
  • 谢谢@CodeManiac!这帮助我修复了它

标签: javascript random numbers shuffle


【解决方案1】:

只需将循环更改为 while 循环并检查数组是否已经没有该值:

let i = 0;
while(i < numBox) {
    let num = Math.floor(Math.random() * highestNumber) + 1;
    if (randomNums.indexOf(num) == -1) {
        randomNums.push(num);
        i++;
    }
}

【讨论】:

  • 对不起,它仍然给出重复的数字
  • 匹配,缺少一个括号。
  • 我通过生成 1 到 10 之间的 5 个数字进行检查,但仍然得到一些重复的数字
  • 啊,推送数据`${num}`中有一个空格。现在你可以再试一次
  • 如果你使用的是 ES7,你可以使用 array.includes() 代替 array.indexOf() 方法来检查数组中是否存在一个项目。
【解决方案2】:

您可以简单地生成并验证它是否存在,直到获得必要的随机唯一数字

while (randomNums.length < numBox) {
    let num = Math.floor(Math.random() * highestNumber) + 1;
    if (randomNums.indexOf(num) === -1) randomNums.push(num);
}

【讨论】:

    【解决方案3】:

    这是一种避免while() 循环的方法。

    1. 用从 1 到最大值的数字填充数组
    2. 随机化数组(我从 this answer 借用了 Fisher-Yates 算法)
    3. 从数组中挑选前 N 项

    function random() {
      let randomNums = [];
    
      // Get how many random numbers to output
      let numBox = document.querySelector('.numBox').value;
    
      // Get the highest number range should go to (ex. 1-70)
      let highestNumber = document.querySelector('.highestNumber').value;
    
      // Loop to generate random numbers and push to randomNums array
      for (let i = 1; i <= highestNumber; i++) {
        randomNums.push(i)
      }
    
      randomNums = shuffle(randomNums).slice(0, numBox);
    
      // Sort numbers from lowest to highest
      randomNums.sort(function(a, b) {
        return a - b;
      });
    
      // Output numbers
      document.querySelector('.randomOutput').innerHTML = randomNums;
    }
    
    function shuffle(a) {
      var j, x, i;
      for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
      }
      return a;
    }
    
    random();
    <input class="numBox" value="4"> out of <input class="highestNumber" value="48">
    <div class="randomOutput"></div>
    <button onclick="random()">randomize</button>

    【讨论】:

      【解决方案4】:

      这是修复它的代码,如果其他人有类似的问题:

      function random() {
          let randomNums = [];
          let included = {};
          let numBox = document.querySelector('.numBox').value;
          let highestNumber = document.querySelector('.highestNumber').value;
      
          for (let i =0; i<numBox; i++) {
              let temp = true;
              while(temp) {
                  let num = Math.floor(Math.random() * highestNumber) + 1;
                  if (included[num] === undefined) {
                      temp = false
                      randomNums.push(` ${num}`)
                      included[num] = num
                     }
              }
          }
          randomNums.sort(function(a, b) {return a - b;});
          document.querySelector('.randomOutput').innerHTML = randomNums;
      }
      

      【讨论】:

        【解决方案5】:

        正如@CodeManiac 提到的,在@BilalSiddiqui 解决方案中使用“Set”。

        let randomNums = new Set();
        while(randomNums.size < 5) {
            let num = Math.floor(Math.random() * 10) + 1;
                randomNums.add(num);
        }
        console.log(randomNums)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-08-19
          • 1970-01-01
          • 2011-08-02
          • 2016-01-03
          • 2014-01-29
          • 1970-01-01
          • 2016-07-24
          • 2018-12-17
          相关资源
          最近更新 更多