我正在尝试获取0到100之间的随机数。但我希望它们是唯一的,而不是在一个序列中重复。例如,如果我得到5个数字,它们应该是82,12,53,64,32,而不是82,12,53,12,32我使用了这个,但它在一个序列中生成相同的数字。
Random rand = new Random();
selected = rand.nextInt(100);
发布于 2015-07-27 23:06:10
对于Java 8+,您可以使用Random
的ints
方法获取随机值的IntStream
,然后使用distinct
和limit
将流减少为一些惟一的随机值。
ThreadLocalRandom.current().ints(0, 100).distinct().limit(5).forEach(System.out::println);
如果需要的话,Random
也有创建LongStream
和DoubleStream
的方法。
如果您希望某个范围中的所有(或大量)数字按随机顺序排列,则将所有数字添加到列表中、对其进行混洗并获取前n可能更有效,因为上面的示例当前是通过在请求的范围中生成随机数并将它们传递到一个集合(类似于Rob Kielty's answer)来实现的,这可能需要生成比传递到限制的数量多得多的数量,因为生成新的唯一数字的概率随着找到的每个数字而减少。下面是另一种方式的示例:
List<Integer> range = IntStream.range(0, 100).boxed()
.collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(range);
range.subList(0, 99).forEach(System.out::println);
发布于 2011-11-14 07:45:14
对所有100个数字使用Collections.shuffle()
,并选择前五个数字,如here所示。
发布于 2014-02-21 17:56:20
我觉得这个方法值得一提。
private static final Random RANDOM = new Random();
/**
* Pick n numbers between 0 (inclusive) and k (inclusive)
* While there are very deterministic ways to do this,
* for large k and small n, this could be easier than creating
* an large array and sorting, i.e. k = 10,000
*/
public Set<Integer> pickRandom(int n, int k) {
final Set<Integer> picked = new HashSet<>();
while (picked.size() < n) {
picked.add(RANDOM.nextInt(k + 1));
}
return picked;
}
https://stackoverflow.com/questions/8115722
复制相似问题