For most card games you need to be able to shuffle the deck; that is, put the cards in a random order. In SectionΒ 10.7 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β1β
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.
You can probably figure out how to write randomInt by looking at SectionΒ 10.7, although you will have to be careful about possibly generating indices that are out of range.
Try writing the randomInt and swapCards functions in the commented sections of this active code. 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 check the hints below.
Letβs write the code for the randomInt function. randomInt should take two parameters, low and high, and return a random integer between them, inclusive.
int randomInt(int low, int high) {
---
int randomInt() { #paired
---
int x = random();
---
int y = x % (high - low + 1) + low;
---
int y = x % high; #paired
---
return y;
}
---
return x;
} #paired