我想创建一个函数,在数组中选择一个随机数字,并避免下次选择相同的数字。
这是我的代码(它在某些时候工作,主要是inf循环)
请帮助我,谢谢。
private static int pick(int[] x) {
int upperbound = x[x.length-1];
int lowerbound = x[0];
int count=0;
int ranvalue;
int ranindex;
Random rand = new Random();
do{
ranindex = rand.nextInt(upperbound-lowerbound) + lowerbound;
count++;
}while(x[ranindex]==-1||count!=x.length-1);
ranvalue=x[ranindex];
x[ranindex]=-1;
return ranvalue;
}
如果你的数组大小为 n,那么你最多可以获得 n 个不同的索引。我建议如下:
- 创建一个数组,其中包含从
0
到n-1
的数字。 - 洗牌。
- 在每一步中,从此数组中获取下一个元素,并将其用作源数组的偏移量。
您还应该将此逻辑包装到如下所示的类中:
public class Picker {
private int[] source;
private List<Integer> offsets;
private int currentIndex = 0;
public Picker(int[] source) {
this.source = source;
Integer[] indexes = new Integer[source.length];
for(int i=0;i<source.length;i++) {
indexes[i] = i;
}
this.offsets = Arrays.asList(indexes);
Collections.shuffle(this.offsets);
}
public Integer next() {
return source[offsets.get(currentIndex++)];
}
}
例:
public static void main(String[] args) {
int[] source = {8,3,5,9};
Picker picker = new Picker(source);
for(int i = 0; i<4;i++) {
System.out.println(picker.next());
}
}
输出:
5
3
8
9
编辑 : 甚至更简单 :
Integer[] source = {8,3,5,9};
//Copy the source and shuffle it
List<Integer> dest = Arrays.asList(source);
Collections.shuffle(dest);
//Then display
for (int i = 0;i<source.length;i++) {
System.out.println(dest.get(i));
}