Reputation: 5086
I have the following java code, which is supposed to "shuffle" cards in a deck. The deck is an arraylist containing card objects.
private void ShuffleDeck() {
//Number of cards in deck
int deckSize = deck.size();
//Swapping 100 cards
for(int i = 0; i < 15; i++) {
//Generating two random card indexes
int indexA = (int) ((Math.random() * deckSize-1));
int indexB = (int) (Math.random() * deckSize-1);
System.out.println(indexA + " " + indexB);
//Getting objects
Card cardA = deck.get(indexA);
Card cardB = deck.get(indexB);
//Temporaily removing these cards from deck
deck.remove(cardA);
deck.remove(cardB);
//Swapping around the two cards
deck.add(indexA, cardB);
deck.add(indexB, cardA);
}
}
However, when I run this method some cards seem to "disappear" from the deck... Any suggestions as to why this is? :)
Upvotes: 0
Views: 176
Reputation: 16037
Assuming deck
is a List<Card>
(including ArrayList
, etc.):
public void shuffleDeck() { // please use camelCase method names
Collections.shuffle(deck);
}
Don't reinvent the wheel.
Upvotes: 9