Deck of Cards

Design the data structures for a generic deck of cards. Explain how you would subclass the data structures to implement blackjack.

Solution

Handle Ambiguity

First, we need to recognize that a "generic" deck of cards can mean many things. Generic could mean a standard deck of cards that can play a poker-like game, or it could even stretch to Uno or Baseball cards. It is important to ask your interviewer what she means by generic.

Let's assume that your interviewer clarifies that the deck is a standard 52-card set, like you might see used in a blackjack or poker game.

Define the Core Objects

In card games, suit is one of the categories into which the cards of a deck are divided.

First we define an enum called Suit

enum class Suit {
    Club,
    Diamond,
    Heart,
    Spade
}

Then we define class of Card

class Card {
public:
    Card(int _value, Suit _suit) {
        value = _value;
        suit = _suit;
    }
private:
    int value;
    Suit suit;
}

Then we define the deck class

class Deck {
public:
    Deck();
    Deck(int num);

private:
    int numOfCards;
    Card cards[52];
}

Last but not least, we define a class that represents the player

class Hand {
public:
    Hand();
    Hand(vector<Card> _cards) {
        cards = _cards;
    };
private:
    vector<Card> cards;
};

Analyze Relationships

The deck represents the remaining cards on the table, we can initialized the deck with cards ranging from 1 to 52 cards. So this is a one-to-many relationship between deck and card.

We also define a class called Hand which represents our players, each player will be holding any number of cards.

Investigate Actions

Now we have our core objects and the relationships between them figured out. Let's add some actions to them.

After initializing the deck, we need to shuffle our deck for randomness before playing. And also we need to deal a hand of cards at the beginning and deal one card at a time.

And for Hand class, we need to calculate the score of all cards it has. When dealer gives a card, it needs to be able to add it.

Blackjack

Now let's build a blackjack game, so we need to know the value of the cards. Face cards are 10 and ace is 11.

class BlackJackHand: Hand {
public:
    int score();
    bool busted();
    bool is21();
    bool isBlackjack();
}

class BlackJackCard: Card {
public:
    int value();
    int minValue();
    int maxValue();
    bool isAce();
    bool isFace();
}

results matching ""

    No results matching ""