我想创建一个函数,在数组中选择一个随机数,避免在下次选择相同的数字
这是我的代码(它在某个时候工作,主要是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;
}
答案 0 :(得分:5)
如果您的数组的大小为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));
}