我有一个函数,它接受用户输入以告诉它要输出多少个随机数,以及要在其之间进行随机数运算的范围(例如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;
}
答案 0 :(得分: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 :(得分:0)
您可以简单地生成并验证它是否存在,直到获得必要的随机唯一编号为止
while (randomNums.length < numBox) {
let num = Math.floor(Math.random() * highestNumber) + 1;
if (randomNums.indexOf(num) === -1) randomNums.push(num);
}
答案 2 :(得分:0)
这是一种避免while()
循环的方法。
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>
答案 3 :(得分:0)
如果其他人有类似的问题,这是修复它的代码:
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;
}
答案 4 :(得分:0)
,在@BilalSiddiqui解决方案中使用“设置”。
solve_ivp