[英]Generate a List of Unique Random Numbers
So, I have a random number generator, where it generates 10 numbers between 1 and whatever the user inputs as the maximum. 因此,我有一个随机数生成器,它会生成1到用户输入的最大值之间的10个数字。 It worked well, but I want to make it so it doesn't generate duplicate numbers. 效果很好,但我想制作它,以免产生重复的数字。 So, if it generates a 5, none of the other numbers can be 5. 因此,如果生成5,则其他任何数字都不能为5。
You can try rejection sampling. 您可以尝试剔除采样。 Begin with an empty set. 从一个空集开始。 Generate a number, if it is in the set, try again. 生成一个数字(如果它在集合中),请重试。 That is to say keep picking until you find a number not in the set. 也就是说,继续选择直到找到不在集合中的数字。 Once you find a new number add it to the set and then return it to the user. 找到新号码后,将其添加到集合中,然后将其返回给用户。
Of course if a large amount of numbers have been generated, say k and the upper bound is n, then the time to get a new number follows a geometric distribution (with success probability (nk)/n), so the expected number of samplings required before you find a unique number is n/(nk). 当然,如果生成了大量数字,例如k,上限为n,那么获取新数字的时间将遵循几何分布(成功概率(nk)/ n),因此预期的采样数找到唯一编号之前需要的编号是n /(nk)。
If you have a small maximum, you can use Collection.shuffle() a list of unique values. 如果最大值很小,则可以使用Collection.shuffle()唯一值列表。 From this you can select 10 elements. 从中可以选择10个元素。
You are not the first to ask this question. 您不是第一个提出这个问题的人。 See https://crypto.stackexchange.com/questions/1379/how-to-generate-a-list-of-unique-random-strings for a general answer. 有关一般答案,请参见https://crypto.stackexchange.com/questions/1379/how-to-generate-a-list-of-unique-random-strings 。
In order to ensure that the number is not a duplicate, store the found numbers in Java SET so that adds only if there is no duplicate inside it. 为了确保该数字不是重复的,请将找到的数字存储在Java SET中,以便仅在其中没有重复的情况下才添加。
Algorith for random generation can be something like: 用于随机生成的算法可以是:
take the system time as your seed value
use this to get the random numbers
suppose user says number between 1-100
so take system milliseconds%100 so time always changes so maximum probability that you get random numbers.
So, always take the seed value mod(%) your upper bound in this case its 100. 因此,在这种情况下,始终将种子值mod(%)的上限设为100。
int i = 0, r = 0;
boolean ch = true;
int[] list = new int[num];
while (i < num)
{
r = rnd.nextInt(num);
ch = true;
for (int j = 0; j < i; j++)
if (r == list[j])
{
ch = false;
break;
}
if (ch)
{
list[i] = r;
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.