更新时间:2023-02-05 17:58:49
您正在有效地寻找整数的随机排列从 0
到 n-1
。
You're effectively looking for a random permutation of the integers from 0
to n-1
.
你可以将 0
中的数字放入 n-1
到 ArrayList
,然后调用 Collections.shuffle()
, n逐个从列表中获取数字:
You could put the numbers from 0
to n-1
into an ArrayList
, then call Collections.shuffle()
on that list, and then fetch the numbers from the list one by one:
final int n = 4;
final ArrayList<Integer> arr = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++) {
arr.add(i);
}
Collections.shuffle(arr);
for (Integer val : arr) {
System.out.println(val);
}
Collectons.shuffle()
保证所有排列都以相同的可能性发生。
Collectons.shuffle()
guarantees that all permutations occur with equal likelihood.
如果您愿意,可以将其封装到 Iterable
:
If you wish, you could encapsulate this into an Iterable
:
public class ChooseUnique implements Iterable<Integer> {
private final ArrayList<Integer> arr;
public ChooseUnique(int n) {
arr = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++) {
arr.add(i);
}
Collections.shuffle(arr);
}
public Iterator iterator() {
return arr.iterator();
}
}
当你迭代这个类的一个实例时,它产生随机排列:
When you iterate over an instance of this class, it produces a random permutation:
ChooseUnique ch = new ChooseUnique(4);
for (int val : ch) {
System.out.println(val);
}
在一次特定的运行中,打印出 1 0 2 3
。
On one particular run, this printed out 1 0 2 3
.