问题描述
我试图获得0到100之间的随机数。但是我希望它们是唯一的,而不是按顺序重复。例如,如果我得到5个数字,它们应该是82,12,53,64,32而不是82,12,53,12,32
我使用了它,但它在序列中生成相同的数字。
I'm trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32 and not 82,12,53,12,32I used this, but it generates same numbers in a sequence.
Random rand = new Random();
selected = rand.nextInt(100);
推荐答案
- 添加每个号码该范围按结构顺序排列。
- 它。
- 取第一个'n'。
- Add each number in the range sequentially in a list structure.
- Shuffle it.
- Take the first 'n'.
这是一个简单的实现。这将打印1-10范围内的3个唯一随机数。
Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.
import java.util.ArrayList;
import java.util.Collections;
public class UniqueRandomNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<11; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<3; i++) {
System.out.println(list.get(i));
}
}
}
正如Mark Byers在现在删除的答案中指出的那样,使用原始方法修复的第一部分是仅使用一个 Random
实例。
这就是导致数字相同的原因。 Random
实例以当前时间(以毫秒为单位)播种。对于特定的种子值,,随机实例将返回与伪随机数字完全相同的序列。
That is what is causing the numbers to be identical. A Random
instance is seeded by the current time in milliseconds. For a particular seed value, the 'random' instance will return the exact same sequence of pseudo random numbers.
这篇关于在Java中生成唯一随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!