如何得到一定范围内一定数量的唯一随机数?

How to get a certain number of unique random numbers in a certain range?

我有一个函数,它接受用户输入来告诉它要输出多少个随机数,以及使随机数介于(比如 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;
}

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

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

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

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

这是避免 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>

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

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

如@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)