在数组中生成唯一数字 [英] Generate Unique Numbers in Array
问题描述
我是javascript的新手,正在尝试使Functions
,For
循环和If
语句变得舒适.我正在做一个简单的练习,该练习从一个函数调用中生成5个随机数.我努力拼凑的一点逻辑是比较Math.random创建的数字,这些数字被推到数组中.最好的方法来确保要推入数组的所有数字都是唯一的(无重复)?我会在For
代码块中添加一个If
语句来检查每个数字,如果它们匹配,请重新运行Math.random函数?试图找出这是否是解决问题的最佳方法.
I'm new to javascript and trying to get comfy with Functions
, For
loops, and If
statements. I'm working on a simple exercise that generates 5 random numbers from a function call. One bit of logic that I'm struggling with putting together is comparing the numbers created by Math.random that are pushed into an array. What's the best method to use to ensure that all numbers to push to the array are unique (no duplicates)? Would I add an If
statement in the For
codeblock that checks every number, and if they match, rerun the Math.random function? Trying to figure out if that's the best way to approach the problem.
function randoNumbers(min, max){
let randomNumbers = [];
for (let counter = 0; counter < 5 ; counter++){
randomNumbers.push(Math.floor(Math.random() * (max - min) + +min));
}
console.log(randomNumbers);
}
randoNumbers(1, 10);
推荐答案
一个非常简单的解决方案是生成数字,直到生成的数字尚未包含在数组中,然后将其推送到结果数组中:
A very plain solution would be to generate numbers until the generated number is not already included in the array, and then push it to the result array:
function randoNumbers(min, max) {
const randomNumbers = [];
for (let counter = 0; counter < 5; counter++) {
let num;
do {
num = Math.floor(Math.random() * (max - min) + min);
}
while (randomNumbers.includes(num))
randomNumbers.push(num);
}
console.log(randomNumbers);
}
randoNumbers(1, 10);
为获得更好的复杂性,您可以使用Set
代替(set.has
比arr.includes
更快):
For slightly better complexity, you could use a Set
instead (set.has
is quicker than arr.includes
):
function randoNumbers(min, max) {
const set = new Set();
for (let counter = 0; counter < 5; counter++) {
let num;
do {
num = Math.floor(Math.random() * (max - min) + min);
}
while (set.has(num))
set.add(num);
}
console.log([...set]);
}
randoNumbers(1, 10);
这篇关于在数组中生成唯一数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!