简体   繁体   English

如何创建不重复的随机数数组

[英]How to approach creating array of random numbers with no repeats

I've created a lotto number generator and am having trouble making sure no two sets of numbers come out the same.我创建了一个乐透号码生成器,但无法确保没有两组号码相同。 I want to first check that the next generated number doesn't match a previous one in the array, if it does then generate a new number.我想首先检查下一个生成的数字是否与数组中的前一个数字不匹配,如果匹配则生成一个新数字。

The code: https://codesandbox.io/s/billowing-leaf-oqdt3?file=/index.html代码: https://codesandbox.io/s/billowing-leaf-oqdt3?file=/index.html

You can do it step by step by replacing what you have line 46 by:您可以通过将第 46 行替换为:

// Get a random number
var rnd = rand(high);
// If it is already in the array, get another
while (numList.includes(rnd)) {
    rnd = rand(high);
}
// Now you know the value is unique, so you can add it to the list.
numList.unshift(rnd);

use a hash:使用 hash:

var numberHash = {}
var num1=generateNum(numberHash);
var num2=generateNum(numberHash);

function generateNum(numberHash) {
  var num = rand();
  while(numberHash[num]) {
    num = rand();
  }
  numberHash[num]=true;
  return num;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM