在数组中生成唯一数字 [英] Generate Unique Numbers in Array

查看:84
本文介绍了在数组中生成唯一数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript的新手,正在尝试使FunctionsFor循环和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.hasarr.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆