我的问题是我希望我的程序在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
答案 0 :(得分:8)
您正在有效地查找从0
到n-1
的整数的随机排列。
您可以将0
到n-1
的数字放入ArrayList
,然后在该列表上调用Collections.shuffle()
,然后逐个从列表中提取数字:
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()
保证所有排列都以相同的可能性发生。
如果您愿意,可以将其封装到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();
}
}
当您遍历此类的实例时,它会产生随机排列:
ChooseUnique ch = new ChooseUnique(4);
for (int val : ch) {
System.out.println(val);
}
在一次特定的运行中,打印出1 0 2 3
。
答案 1 :(得分:0)
您可以填写(如果您不需要太多数字)ArrayList<Integer>
,数字范围为0 - 3.然后您使用Random.nextInt(list.size())
获得随机索引,从列表中获取数字和removeAt
您索引处的条目。
答案 2 :(得分:0)
如果你的范围在某种类型的数组中,那么只需在数组的长度上使用随机数。
例如,如果您有一个名为range
的int数组。然后你可以使用:
java.utils.Random randomGenarator = new java.utils.Random();
return range[randomGenarator.nextInt(range.length)];