2017-10-07 43 views
1

我目前有一個隨機混合ArrayListJava-將元素從ArrayList移動​​到數組

public static void main(String[] args) { 
    ArrayList<Integer> solution = new ArrayList<>(); 
    for (int i = 1; i <= 48; i++) { 
     solution.add(i); 
    } 
    Collections.shuffle(solution); 

這給我一個ArrayList與數字1-48隨機混合。現在我有4個數組,我想隨機添加ArrayList的元素而不重複。

int[] heartsRow = new int[14]; 
int[] diamondsRow = new int[14]; 
int[] spadesRow = new int[14]; 
int[] clubsRow = new int[14]; 

新數組包含14個元素的原因是因爲前兩個元素總是相同。

heartsRow[0] = 1; 
    heartsRow[1] = 0; 
    diamondsRow[0] = 14; 
    diamondsRow[1] = 0; 
    spadesRow[0] = 27; 
    spadesRow[1] =0; 
    clubsRow[0] = 40; 
    clubsRow[1] = 0; 

我想用ArrayList的非重複元素完全填充每個陣列。

回答

0

您可以製作4 for循環,從0到11,12到23,24到35和36到47,並添加到您的列表中。

for (int i = 0; i < 12; i++) 
    heartsRow[i + 2] = solution.get(i); 

for (int i = 0; i < 12; i++) 
    diamondsRow[i + 2] = solution.get(i + 12); 

for (int i = 0; i < 12; i++) 
    spadesRow[i + 2] = solution.get(i + 24); 

for (int i = 0; i < 12; i++) 
    clubsRow[i + 2] = solution.get(i + 36); 
1

你可以使用一個計數循環在列表中, 增量在每個步驟中,計數器4,和 分配元件陣列與調整偏移:

for (int i = 0; i + 3 < solution.size(); i += 4) { 
    int j = i/4; 
    heartsRow[2 + j] = solution.get(i); 
    diamondsRow[2 + j] = solution.get(i + 1); 
    spadesRow[2 + j] = solution.get(i + 2); 
    clubsRow[2 + j] = solution.get(i + 3); 
} 
相關問題