< previous page page_1095 next page >

Page 1095
herited from the CardPile class. However, the private part declares a member function named Merge. This function is not accessible to clients of CardDeck. As we see shortly, the Merge function is a helper function that is used by the Shuffle member function.
Now we implement the CardDeck member functions. We begin with the class constructor.
The class constructor CardDeck ()
When a CardDeck class object is created, the constructor for its base class (CardPile) is implicitly executed first, creating an empty list. Starting with the empty list, we can generate the first cardthe ace of clubsand insert it into the list. The balance of the 52 cards can be generated in a loop. After every 13th card, we increment the suit and reset the rank to one.
Set tempCard.suit = CLUB
Set tempCard.rank = 1
InsertTop(tempCard)              // Insert into deck
FOR count going from 2 through 52
  Increment tempCard.rank
  IF tempCard.rank > 13
      Increment tempCard.suit
      Set tempCard.rank = 1
  InsertTop(tempCard)            // Insert into deck

Although we don't use the rank of a card, we leave it there because we may want to print out the contents of the list during debugging. Also, the CardDeck class may be used in other simulations. The class should be tested with a complete representation of a deck of cards.
Shuffle (In: numberOfShuffles)
When a human shuffles a deck of cards, he or she divides the deck into two nearly equal parts and then merges the two parts again. This process can be simulated directly (a simulation within a simulation). The list representing the deck can be divided into two lists, halfA and halfB. Then these two lists can be merged again. We use a random number generator to determine how many cards go into halfA. The rest go into halfB.
Through the header file stdlib.h, the C++ standard library provides two functions for producing random numbers. The first, named rand, has the following prototype:
int rand();

 
< previous page page_1095 next page >