Mind-Boggling Card Trick
September 4, 2018
Today’s exercise is a mind-boggling card trick:
Create a pack of 52 cards, half red, half black, and shuffle them. With the cards face down, turn over the top card. If it is black, add the next card, unseen, to the black stack; if it is red, add the next card, unseen, to the red stack. Add the original top card to the discard stack. Repeat these steps for all the cards in the pack. Now, randomly choose a number less than the size of the smaller of the black and red stacks, choose that many cards randomly from each of the two stacks, and swap those randomly-chosen cards from one stack to the other. The number of black cards in the black stack will equal the number of red cards in the red stack.
Your taks is to write a program to simulate the card trick and confirm that the number of black cards in the black stack equals the number of red cards in the red stack. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
This is indeed a magic trick:
The first phase is not random at all, because the operation ensures that there are the same number of black in the black stack as there are reds in the red stack. Discading the seen cards, ensures that there will remain the exact same number of cards (either of the same color, or the opposite color) to be moved to the other stack.
The second part is just for the spectacle, since it’s an operation that does not change that property (if two cards of the same color are exchanged, then no change; if cards of different colors are exchanged, then either it increments both counts (if the right color leaves each stack), or it decrements both counts (if red leaves the red stack and black leaves the black stack). Randomness does not matter, you could choose the cards you want, as long as you exchange the same number from both stacks :-)
This code almost reads like the assignment to me ;)
A Haskell version.
Here’s a solution in Python.