# 13.6. Shuffling¶

For most card games you need to be able to shuffle the deck; that is, put the cards in a random order. In Section [random] we saw how to generate random numbers, but it is not obvious how to use them to shuffle a deck.

One possibility is to model the way humans shuffle, which is usually by dividing the deck in two and then reassembling the deck by choosing alternately from each deck. Since humans usually don’t shuffle perfectly, after about 7 iterations the order of the deck is pretty well randomized. But a computer program would have the annoying property of doing a perfect shuffle every time, which is not really very random. In fact, after 8 perfect shuffles, you would find the deck back in the same order you started in. For a discussion of that claim, see http://www.wiskit.com/marilyn/craig.html or do a web search with the keywords “perfect shuffle.”

A better shuffling algorithm is to traverse the deck one card at a time, and at each iteration choose two cards and swap them.

Here is an outline of how this algorithm works. To sketch the program, I am using a combination of C++ statements and English words that is sometimes called pseudocode:

for (size_t i = 0; i < cards.size(); i++) {
// choose a random number between i and cards.size()
// swap the ith card and the randomly-chosen card
}


The nice thing about using pseudocode is that it often makes it clear what functions you are going to need. In this case, we need something like randomInt, which chooses a random integer between the parameters low and high, and swapCards which takes two indices and switches the cards at the indicated positions.

Note

If you are even the slightest bit unsure on how to begin coding your program, pseudocode is a great place to start!

You can probably figure out how to write randomInt by looking at Section [random], although you will have to be careful about possibly generating indices that are out of range.

You can also figure out swapCards yourself. I will leave the remaining implementation of these functions as an exercise to the reader.

Try writing the randomInt and swapCards functions in the commented sections of the active code below. Once you’re done with randomInt and swapCards, try using them to implement the Deck member function shuffleDeck. If done correctly, the program should output a shuffled deck of cards. If you stuck, you can reveal the extra problems at the end for help.