VI: The Programmatic Side of Mathematica: The perfect shuffle of a deck of cards

Making a deck of cards requires making a the basic thirteen card values:

Join[Range[2,10], {J, Q, K, A}]

Then, you need to distribute these values among the four suits:

Outer[List, {c, d, h, s}, %]

This set gives four subsets representing each suit, then expresses each value-suit combination as a set. You want to keep the value-suit combinations, but if you want to shuffle the deck, you need to “flatten” the set somewhat to remove the set boundaries for the suits. That would be a call to the Flatten[] function with a “1” as a second parameter, indicating that we know that this set is a superset of four subsets, and we would like to remove the boundaries for the four subsets (the suits) and create a superset of the 52 individual cards:


The cards are in numerical order of clubs, diamonds, hearts and spades. We would now like to shuffle the deck. What would a good dealer do to shuffle a deck? I would guess that he would first split the deck:


That creates that three-layered set of sets of sets again, but this time the middle layer is in two pieces, where the deck was split, rather than being split at each suit. Now, what? Our dealer would likely shuffle the deck. If he is skilled he could do what is known as a perfect shuffle, where the cards from each half-deck are interleaved with cards in the other half:


All of these commands can be nested inside of one command so that we get:

Transpose[Partition[Flatten[Outer[List, {c, d, h, s},
    Join[Range[2,10], {J, Q, K, A}]], 1], 26]]

Oh yeah, and don’t forget to flatten the set again to remove the split in the deck:

Flatten[Transpose[Partition[Flatten[Outer[List, {c, d, h, s},
    Join[Range[2,10], {J, Q, K, A}]], 1], 26]], 1]

I wouldn’t personally use these to play cards at this point, since the cards are still shuffled predictably and reproducibly. In the real world, if it so happened that a dealer shuffled the deck by interleaving the cards, this might still be the result from a new deck. But what you want is for them to be shuffled randomly and not predictably. You may even want to store the array in a variable so you can’t see the deck right away.

So, what is known as the “perfect shuffle” is only “perfect” in the sense that the interleaving of two halves of an ordered deck is done without errors. If all interleavings are perfect beginning with an ordered deck, I would guess that all subsequent deck splittings and interleavings are also repreoducible, and therefore predictable, assuming all shuffles are perfect shuffles. In the real world, random errors would be introduced in the interleavings (two cards slip by on one hand before one slips by on the other for example), which introduce the element of chance in card games.