简体   繁体   English

生成范围内的每个随机数

[英]Generate Every Random Number in a Range

I want to get EVERY random number within a certain range exactly once. 我想在某个范围内的每个随机数刚好得到一次。

For example, if the range was 1-10, I would want every number 1-10 in a random order. 例如,如果范围是1-10,我希望每个数字1-10都以随机顺序排列。 What is a simple, fast, and clean algorithm for doing this? 有什么简单,快速且干净的算法可以做到这一点?

Is there some existing way to do this automatically in Java? 是否有一些现有的方法可以在Java中自动执行此操作?

填充一个包含1-10之间数字的列表,然后使用Collections.shuffle(list);

There's no way from the JDK, but the simplest approach is to use Collections.shuffle() on a list of all the numbers in the range: JDK没有办法,但是最简单的方法是在范围内所有数字的列表上使用Collections.shuffle()

List<Integer> list = new ArrayList<>();
for (int i = 1; i < 11; i++) list.add(i);
Collections.shuffle(list);

then return the contents of list in order 然后按顺序返回列表的内容

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

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