Dealing and Ranking Three-Card Hands With an Extensible Rule Set
Data Structure DesignModel answerLast updated
Build a small card game that deals three cards per player from one deck, ranks hands by category, picks the winner, then extend the ranking with a suit-based category.
Write a program that simulates one round of a simple three-card game. A single shuffled 52-card deck (13 ranks, 4 suits) is shared by all players, and each player is dealt three cards. The program must print every player's hand and announce the winner.
The exercise has two stages. The first ignores suits. The second adds a suit-dependent category, so structure the first stage so that the change is small.
Rules that apply throughout
- Cards are dealt without replacement, so no card repeats within a round.
- Rank order from low to high is 2 through 10, J, Q, K, A. The ace is always high.
- No straights exist. Only the categories listed for the current stage are recognized.
Stage 1: suits are irrelevant
Categories from strongest to weakest:
- Trips: all three cards share a rank.
- Pair: exactly two cards share a rank.
- High card: anything else.
Within a category, hands are compared like this:
- Trips: by the shared rank.
- Pair: first by the rank of the pair, then by the remaining single card.
- High card: by the highest card, then the middle card, then the lowest card.
Stage 2: add a flush
A flush is a hand where all three cards share a suit. The order becomes trips > flush > pair > high card. Two flushes are compared by highest card, then middle, then lowest. Update the program accordingly.
What to decide and state up front
- Number of players (fixed or a parameter; at most 17 fit in one deck).
- What happens when hands are exactly equal in strength: shared win, or an extra tie-break.
- How results are reported (printed, returned, or both).
- Whether the deal can be seeded so tests are reproducible.
What is expected
- Clean representations for cards, the deck and hands.
- Correct detection of each category and correct comparison inside each category.
- A well-defined outcome for exact ties.
- A design where the category order lives in one place, so Stage 2 is a small change.
- Tests showing, for example, that a flush beats a pair in Stage 2 but not in Stage 1.
Hints
Hint 1
Turn each hand into a single comparable key, such as a tuple of (category strength, tie-break ranks...). Then picking the winner is just taking the maximum key.
Hint 2
For tie-break ranks, order the cards by how many times their rank appears, then by rank, both descending. This handles trips, pairs (pair rank before the kicker) and high cards with one rule.
Hint 3
Keep the category order in one table or enum and make each category a small detection rule. Adding the flush then means adding one rule and one entry. Also inject the random source so tests can fix the deal.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key idea is to reduce every hand to a comparable key. Once each hand has a key, determining the winner is a max over keys, and exact ties are simply equal keys.
Representation
- Card: a rank as an integer (2..14, with J=11, Q=12, K=13, A=14) and a suit. Comparing integers avoids the classic bug of comparing labels as strings, where "10" would sort before "2".
- Deck: the 52 combinations of rank and suit. Shuffle with an injectable random generator, then deal by slicing off three cards at a time. Slicing a single shuffled list gives dealing without replacement for free.
- Hand: three cards.
Evaluating a hand
- Count how often each rank appears.
- Sort the distinct ranks by (count descending, rank descending). This gives the tie-break sequence:
- Trips:
[r] - Pair:
[pair rank, kicker] - High card:
[high, mid, low]
- Trips:
- The category is determined by the count pattern:
3is trips,2+1is pair, otherwise high card. In Stage 2, a hand where all suits match is a flush, but only if it is not already trips (which cannot happen with one deck, since three cards of the same rank always have different suits). - The key is
(category_strength, tie_break_sequence). Python tuples and Java comparators on lists compare lexicographically, which is exactly the comparison the rules describe.
Why the one-rule tie-break works
Sorting by count first puts the pair rank ahead of the kicker, so a pair of 5s with an ace loses to a pair of 6s with a 2. Trips have one distinct rank. High cards all have count 1, so they fall back to rank order, giving highest, middle, lowest.
Making Stage 2 a small change
Define categories in one ordered structure:
import random
from collections import Counter
RANKS = {**{str(n): n for n in range(2, 11)}, "J": 11, "Q": 12, "K": 13, "A": 14}
# Weakest to strongest; the list position is the strength.
CATEGORIES = [
("high_card", lambda h: True),
("pair", lambda h: sorted(Counter(c[0] for c in h).values()) == [1, 2]),
# Stage 2 only: ("flush", lambda h: len({c[1] for c in h}) == 1),
("trips", lambda h: len({c[0] for c in h}) == 1),
]
def hand_key(hand):
counts = Counter(c[0] for c in hand)
order = sorted(counts, key=lambda r: (counts[r], r), reverse=True)
strength = max(i for i, (_, test) in enumerate(CATEGORIES) if test(hand))
return (strength, order)
def deal(num_players, rng=random):
deck = [(r, s) for r in range(2, 15) for s in "CDHS"]
rng.shuffle(deck)
return [deck[3 * i: 3 * i + 3] for i in range(num_players)]
def play(num_players, rng=random):
hands = deal(num_players, rng)
keys = [hand_key(h) for h in hands]
best = max(keys)
winners = [i for i, k in enumerate(keys) if k == best]
return hands, winners
To go to Stage 2, uncomment the flush entry between pair and trips. Nothing else changes. Because the strength is the highest matching category, a hand matching several rules resolves to the strongest one, so the order of checks does not matter. A flush's tie-break sequence is automatically high, middle, low because all ranks are distinct (count 1).
Ties
With one deck and suits ignored, two players can easily hold equal-strength hands (for example 9-9-K and 9-9-K with different suits). I would state the policy as shared win: return all indices with the maximum key and print "tie between players X and Y". Inventing a suit order would contradict the stated rules.
Complexity
Per hand the work is constant (three cards). A round costs O(n) for n players for evaluation and the max, plus O(52) to build and shuffle the deck. Memory is O(n) for the hands.
Tests worth writing
- A hand-built example for each category and each tie-break level: trips against trips, pair with a different pair rank, pair with the same rank but different kicker, and high cards that differ only in the lowest card.
- Ace is high: A-K-Q beats K-Q-J.
- Stage 1 versus Stage 2: a flush such as 2-5-9 of one suit loses to a pair in Stage 1 and beats it in Stage 2.
- Exact ties return all tied players.
- A seeded deal gives the same output twice, no card appears twice, and 17 players works while 18 raises a clear error.
Common mistakes
- Comparing rank labels as strings.
- Comparing a pair's kicker before the pair rank.
- Hard-coding category order in several
ifchains, so adding the flush touches multiple places. - Checking categories in the wrong order, for example calling a hand a flush when a stronger category applies.
- Calling the global random generator directly, which makes tests non-reproducible.
- Silently picking the first player on a tie.
- Not guarding against more than 17 players.