选择具有特定范围的唯一随机数

我的问题是我希望我的程序在0到3之间的数字范围内做出四个独特的随机选择我试着在随机类中做到但我不能,如果你可以通过代码帮助它会很棒,我的程序将是这样的事情可以说清楚

my range 0 1 2 3 randomly chosen number 3 0 1 2 randomly chosen number 1 0 2 randomly chosen number 2 0 it will choose 0 and then the program closes 

你有效地寻找从0n-1的整数的随机排列。

您可以将数字从0n-1放入ArrayList ,然后在该列表上调用Collections.shuffle() ,然后逐个从列表中获取数字:

  final int n = 4; final ArrayList arr = new ArrayList(n); for (int i = 0; i < n; i++) { arr.add(i); } Collections.shuffle(arr); for (Integer val : arr) { System.out.println(val); } 

Collectons.shuffle()保证所有排列都以相同的可能性发生。

如果您愿意,可以将其封装为Iterable

  public class ChooseUnique implements Iterable { private final ArrayList arr; public ChooseUnique(int n) { arr = new ArrayList(n); for (int i = 0; i < n; i++) { arr.add(i); } Collections.shuffle(arr); } public Iterator iterator() { return arr.iterator(); } } 

当您遍历此类的实例时,它会生成随机排列:

  ChooseUnique ch = new ChooseUnique(4); for (int val : ch) { System.out.println(val); } 

在一个特定的运行中,这打印出1 0 2 3

您可以填充(如果您不需要太多数字) ArrayList ,数字范围从0到3.然后您使用Random.nextInt(list.size())获得随机索引,从中获取数字列表并removeAt索引处的条目。

如果你的范围在某种类型的数组中,那么只需在数组的长度上使用随机数。

例如,如果您有一个名为range的int数组。 然后你可以使用:

 java.utils.Random randomGenarator = new java.utils.Random(); return range[randomGenarator.nextInt(range.length)];