2 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
假設(shè)cartePresenti從零開(kāi)始。這應(yīng)該有效:
Random r = new Random();
int n = carte.size();
for (int i = n - 1; i > 0; i--) {
int j = r.nextInt(i + 1);
Carta temp = carte.get(i);
carte.put(i, carte.get(j));
carte.put(j, temp);
}

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
使用替代解決方案Collection.shuffle()
:
//List of the indexes of the card in the old map
List<Integer> indexes = new ArrayList<Integer>();
//Map shuffled
Map<Integer, Carta> shuffledCarte = new ArrayMap<Integer, Carta>();
//Collect the indexes
For(int i = 0; i<carte.size(); i++) {
indexes.add(i);
}
//Shuffle the indexes
indexes.shuffle();
//Create the new map, using the shuffled indexes
for(int j = 0; j<carte.size(); j++) {
shuffledCarte.put(j, carte.get(idexes.get(j)));
}
添加回答
舉報(bào)