我有一个int向量,如int[] A = {6, 1, 5, 3, 4, 2}
,我需要在三个步骤中随机选取两个不同的元素,并且每个步骤应该从其他步骤中挑选不同的元素。每次在迭代中从int数组中挑选不同的随机元素?
例如:
- 选择2,5
- 选择6,3
- 选择4,1
我尝试这样做,但我失败了很多次。我会很感激任何帮助。 这是我最后的代码。
public class T8 {
public static void main(String[] args) {
int n=5, d=2, r, i, j;
int[] B = new int [d];
Random rand=new Random();
System.out.println("d = "+d);
Integer[] A = {10,12,3,4,5};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(A));
for(j=0; j<d; j++){
r = rand.nextInt(n);
B[j] = A[r];
System.out.print(B[j]+" ");
list.remove(r);
A = list.toArray(new Integer[0]);
n=n-1;
}
System.out.println("");
for(j=0; j<n; j++){
System.out.print(A[j]+" ");
}
}
}
你试过了什么代码? – markspace 2014-12-07 00:24:27
一种可能的方法是:将选中的每个元素捕获到该选项的变量中,然后将其在原始数组中的索引设置为无效值,然后知道您已经选择了什么。然后把所有的元素都放回去。 – abiessu 2014-12-07 00:31:05
非常感谢,我已经通过加入我自己的代码编辑了帖子。 – John 2014-12-07 00:34:10