简体   繁体   English

在Java中生成一组唯一的随机数

[英]Generate set of unique random numbers in Java

I want to create 10 random numbers in the range 0-500. 我想在0-500范围内创建10个随机数。 But the problem is that I want those numbers to be unique. 但问题是我希望这些数字是唯一的。 For 2 random numbers i could create something as the following: 对于2个随机数,我可以创建如下内容:

int randomItem1 = r.nextInt(500);
int randomItem2 = r.nextInt(500);
while(randomItem1==randomItem2){
    randomItem1=randomItem();
    randomItem2=randomItem();
}

But if I do this for 10, I think that the while it will stack. 但是,如果我这样做10,我认为它会堆叠。 And I'm saying this because I'm trying to create a huge algorithm which is trying to make continuous evaluations and i want continously to take 10 random and unique numbers. 而且我这样说是因为我正在尝试创建一个巨大的算法,它试图进行连续的评估,我想要不断地获取10个随机和唯一的数字。 I don't know what to do. 我不知道该怎么办。 Any ideas or suggestions? 任何想法或建议?

Looks like you are storing these in individual variables. 看起来您将这些存储在单个变量中。 The "normal" place to store groups of items like this would usually be in a list or array. 存储此类项目组的“正常”位置通常位于列表或数组中。

In this case, store them in a "set" data structure instead. 在这种情况下,请将它们存储在“set”数据结构中。 It will not allow duplicates. 它不允许重复。

Set documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html 设置文档: http//docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html

Set set = new HashSet();

while (set.size() < 10) {
    set.add(r.nextInt(500));
}

Java Collections has a shuffle method. Java Collections有一个shuffle方法。 You can put your numbers into an ArrayList and then shuffle its content. 您可以将您的数字放入ArrayList,然后将其内容随机播放。 If the ArrayList contains n numbers, calling the shuffle method, would give you the same ArrayList containing n numbers but arranged randomly. 如果ArrayList包含n个数字,则调用shuffle方法将为您提供包含n个数字但随机排列的相同ArrayList。

for(int i=0;i<10;i++){
list.add(i);  // list contains: [0,1,2,3,4,5,6,7,8,9]
}
Collections.shuffle(list);// list now contains: [0, 9, 3, 1, 5, 8, 7, 2, 6, 4]

Make a LinkedList of the numbers from 1-500 and shuffle one out of them each time you use a number using The Fisher-Yates shuffle . 每次使用Fisher-Yates shuffle使用数字时,从1-500创建一个数字的LinkedList并将其中的一个洗牌

This will give you guaranteed sane (constant time) performance for each number pulled. 这将为您提供每个拉出数字的保证理智(恒定时间)性能。

I would use an array, and store the numbers as they're generated into that array. 我会使用一个数组,并将它们生成的数字存储到该数组中。 You would generate a new random, then need to iterate through your array up to your number count, checking to see if it matched any you have previously created. 您将生成一个新的随机数,然后需要迭代您的数组直到您的数字计数,检查它是否与您之前创建的任何匹配。

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

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