使用 JavaScript 选择不重复的随机数
Picking Non-duplicate Random Numbers using JavaScript
如何在没有重复号码的情况下随机抽取 5 个彩票号码?下面的代码是我目前所拥有的,我只是不知道在哪里插入代码来循环挑选重复的数字并重新分配新的数字?我试过添加 if 和 else 以及 forEach 函数,但它没有用。这是我到目前为止的代码。提前谢谢你。
let lotto = [];
for(let i = 0; i < 5; i++){
lotto[i] = Math.floor(Math.random() * 69) + 1;
}
const sorting = lotto.sort((a,b) => a - b);
console.log(sorting);
两种解决方案:
- 创建一个号码列表,然后从中选择(并删除)5 个。
- 创建一个不断生成数字的循环,直到它有 5 个唯一的数字。
您的尝试可以适用于解决方案 2:
let lotto = [];
while(lotto.length < 5) {
console.log('Got', lotto.length, 'numbers!');
// Changed 69 to 5 to "force" clashes (well, make it very likely)
const num = Math.floor(Math.random() * 5) + 1;
if (!lotto.includes(num)) lotto.push(num);
}
const sorting = lotto.sort((a, b) => a - b);
console.log(sorting);
考虑到该进程将 运行 至少一次,最好的解决方案是使用 do while 循环并验证该数字是否已存在于列表中。
const lotto = [];
do {
const random = Math.floor(Math.random() * 69) + 1;
if(!lotto.includes(random)) lotto.push(random);
} while(lotto.length < 5);
const sorting = lotto.sort((a, b) => a - b);
console.log(sorting);
如何在没有重复号码的情况下随机抽取 5 个彩票号码?下面的代码是我目前所拥有的,我只是不知道在哪里插入代码来循环挑选重复的数字并重新分配新的数字?我试过添加 if 和 else 以及 forEach 函数,但它没有用。这是我到目前为止的代码。提前谢谢你。
let lotto = [];
for(let i = 0; i < 5; i++){
lotto[i] = Math.floor(Math.random() * 69) + 1;
}
const sorting = lotto.sort((a,b) => a - b);
console.log(sorting);
两种解决方案:
- 创建一个号码列表,然后从中选择(并删除)5 个。
- 创建一个不断生成数字的循环,直到它有 5 个唯一的数字。
您的尝试可以适用于解决方案 2:
let lotto = [];
while(lotto.length < 5) {
console.log('Got', lotto.length, 'numbers!');
// Changed 69 to 5 to "force" clashes (well, make it very likely)
const num = Math.floor(Math.random() * 5) + 1;
if (!lotto.includes(num)) lotto.push(num);
}
const sorting = lotto.sort((a, b) => a - b);
console.log(sorting);
考虑到该进程将 运行 至少一次,最好的解决方案是使用 do while 循环并验证该数字是否已存在于列表中。
const lotto = [];
do {
const random = Math.floor(Math.random() * 69) + 1;
if(!lotto.includes(random)) lotto.push(random);
} while(lotto.length < 5);
const sorting = lotto.sort((a, b) => a - b);
console.log(sorting);