我有一個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