# How do I shuffle cards for a card game?

I am trying to develop an card game for Android Can anyone suggest me how to write code for effectively shuffling the playing cards?

Card shuffling is an algorithm which is easy to write intuitively, and get entirely wrong by doing so. There's a good reference for implementing card shuffling correctly on Wikipedia. What I'm presenting here is a very slightly simplified version of the algorithm covered on that page under The modern algorithm.

Here's the basic idea, in plain english:

Consider a deck of cards. For this discussion, you can have any number of cards in the deck, and they may start in any order.

We're going to be talking about "position" in the deck, where "position" is how many cards are higher in the deck than the card in that position. For example, the card on top of the deck is at position 0, the card beneath that is at position 1 (because there is 1 card higher than it -- the top card), and in a standard 52-card deck, the bottom card is at position 51, as 51 cards are higher than it in the deck.

Now, we consider each position in the deck, one at a time, starting from the bottom, and working our way up to the top.

For each position, we randomly select one of the cards which is at that position or at a lower-numbered position (remember, the top of the deck is 0, and we're working our way up from the bottom of the deck, so for each position, you're effectively picking up all the cards at and above that position and randomly picking one of those cards).

When we have made the random selection, we swap the card at the position we're currently considering with the card we randomly selected. If we randomly selected the card which was already in that position, then no swap is performed.

After swapping (or not swapping, if we randomly selected the card which was already in the position we were considering), we move on to the next position in the deck and continue.

In pseudocode, with n being the number of cards in the deck, and a being an array representing the deck, the algorithm looks like this:

for each i in [n .. 1] do
j ← random integer in [ 0 .. i ]
exchange a[j] and a[i]


You first define a sequence of all the cards you want to shuffle:

List<Card> shuffled = new ArrayList<Card>();


Then you walk through every position in the sequence and assign it a card randomly.

Random random = new Random();
for (int i = shuffled.size() - 1; i >= 0; i--) {
int j = random.nextInt(i + 1);

/* swap cards i,j */
Card card = shuffled.get(i);
shuffled.set(i, shuffled.get(j));
shufflet.set(j, card);
}


Now shuffled is a random sequence of all of your cards.

I'd like to chime in and mention "format preserving encryption" as a method for shuffling cards in a game.

Essentially what you'd have is an encryption algorithm that takes in a value 0 to 51, and a key (shuffle seed) and spits out a value 0 to 51. Since encryption is reversible by definition that means any 2 input numbers cannot encrypt to the same output number, which means if you encrypted 0 to 51, you'd get 0 to 51 as output in a different order. In other words you have your shuffle and don't even need to do any actual shuffling.

In this case you'd have to make or find an encryption algorithm that took in 6 bits and spit out 6 bits (0-63). To draw the next card from the deck you'd have an index variable which started at zero, you'd encrypt that index, increment the index and look at the value that came out of the cipher. If the value is >= 52, you ignore it and generate a new number (and increment the index again of course). Since encrypting 0-63 will result in 0-63 as output, in a different order, you are just ignoring any value that comes out >= 52 so that you have your algorithm that takes in 0-51 and spits out 0-51.

To reshuffle the deck, set the index back to zero and change the encryption key (shuffle seed).

Your algorithm doesn't need to be cryptographic quality (and it shouldn't be, cause that would be computationally expensive!). One really good way to come up with a custom sized encryption algorithm like this would be to use a feistel network, which lets you customize size and quality depending on your needs. For the round function of the feistel network, I'd recommend something like murmurhash3 because it's fast and has a good avalanche effect, which would make the shuffles appear well randomized.

Check out my blog post for even more detailed info and source code: http://blog.demofox.org/2013/07/06/fast-lightweight-random-shuffle-functionality-fixed/

• This answer as it currently is phrased doesn't help much when the URL inevitably falls off the surface of the Internet. Consider elaborating in the answer on the salient points of the linked article, so that the answer can stand on its own. – Lars Viklund Apr 4 '15 at 13:34
• Good point Lars, updated with more info so that a reader can at least look for more info on all the specific components of a solution to card shuffling using format preserving encryption. Thanks! – Alan Wolfe Apr 4 '15 at 14:59

The java 1.5 enum tutorial has a interesting way to implement a deck of cards, building up the deck, shuffling and dealing. All very simple using enums and Collections

public class Card {
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}

public Rank rank() { return rank; }
public Suit suit() { return suit; }
public String toString() { return rank + " of " + suit; }

private static final List<Card> protoDeck = new ArrayList<Card>();

// Initialize prototype deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
}

public static ArrayList<Card> newDeck() {
return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
}
}


And the class to manage the deck.

public class Deal {
public static void main(String args[]) {
int numHands = Integer.parseInt(args[0]);
int cardsPerHand = Integer.parseInt(args[1]);
List<Card> deck  = Card.newDeck();
Collections.shuffle(deck);
for (int i=0; i < numHands; i++)
System.out.println(deal(deck, cardsPerHand));
}

public static ArrayList<Card> deal(List<Card> deck, int n) {
int deckSize = deck.size();
List<Card> handView = deck.subList(deckSize-n, deckSize);
ArrayList<Card> hand = new ArrayList<Card>(handView);
handView.clear();
return hand;
}
}


Simply use a function like itertools like there on Python . I am not aware of the name of the same function in Java try ".http://code.google.com/p/neoitertools/"

Find out all the permutations of the object called "cards"

    ArrayList deckCards = new ArrayList<Card>();