Extensible Card Hand Evaluator with Pluggable Rules
Data Structure DesignModel answerLast updated
Design and incrementally build a card-hand evaluator that ranks hands, resolves ties deterministically, adds new categories, and applies a swappable discard rule.
Extensible Card Hand Evaluator with Pluggable Rules
You are building a small card-game engine. The program receives a set of players, each holding a hand of cards, evaluates every hand, determines a winner, and returns a structured log of the entire game. The exercise is incremental: each part introduces a new rule, and the design should absorb those additions without rewriting what already works.
Card representation: A card has an integer rank (2–10, with 11 = Jack, 12 = Queen, 13 = King) and a suit. How ace is represented is intentionally left open — clarify it before coding.
Working assumption: Each hand contains three cards — the smallest count that can produce three of a kind. Verify this and the other open points with your interviewer.
Clarifying Questions to Ask First
- How many cards per hand, and how many players per game?
- Is an ace represented as 1, 14, or something else, and does it rank low or high?
- When two hands fall in the same category, what breaks the tie (e.g., rank of the triple, then kickers)? Can a game end in a draw?
- What does the returned log need to contain — one structured record per event, or a flat list of strings?
- Are hands provided as input, or should the engine shuffle and deal from a deck?
Part 1 — Three of a Kind, Pair, High Card
Implement evaluation and comparison across three categories, ordered strongest to weakest: three of a kind > pair > high card.
Run a single game: evaluate every hand, identify the winner, and return the game log as a value (do not print it).
What to show:
- A
CardandHandmodel that tracks rank, suit, and evaluated category explicitly - Deterministic tie-breaking within each category
- The log accumulated during the game and returned, not side-effected
- A structure that treats the category list and comparison logic as extension points
Part 2 — Insert a Flush Category
Add a flush: a hand whose three cards all share the same suit. The updated order is: three of a kind > flush > pair > high card.
What to show:
- How inserting a new category between existing ones avoids touching the comparison logic
- How two flush hands are ranked against each other
- What happens when a hand qualifies for more than one category (e.g., three of a kind in the same suit) — define and state the priority rule
Part 3 — Add a Swappable Discard Rule
Before hands are compared, apply a discard rule that eliminates certain hands from the game. The specific rule for this part: any hand that is not exactly a pair is discarded, and that player drops out before comparison begins.
The rule is expected to change in future iterations, so the design should make swapping it straightforward.
Clarifying questions for this part:
- Does three of a kind count as "contains a pair" for the purpose of this rule, or is it strictly excluded?
- A flush ranks above a pair but contains no pair — is a flush hand discarded under this rule?
- What is the result when every hand is discarded, or exactly one remains?
- Should each discard appear in the log, and how much detail is expected?
What to show:
- Where the discard rule lives in the design and how it could be replaced with a different rule
- Correct handling of all edge cases the rule introduces
- Log entries that make each discard and the final outcome fully traceable
Hints
Hint 1
Start by separating concerns into at least four things: a Card/Hand model, a category evaluator, a comparison strategy, and a game runner that owns the log. If you mix these, every new rule forces edits in multiple places.
Hint 2
Represent hand categories as ordered values (an enum with an explicit numeric rank, or a list that defines precedence). Then inserting a flush between existing categories is a one-line change, not a rewrite of comparisons.
Hint 3
Treat the discard rule as a strategy or a simple callable — something the game runner applies before comparison, not something baked into hand evaluation. That way swapping it in Part 4 costs one substitution.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core design challenge is extensibility. Each part adds a rule, and the interviewer is watching whether you reach for copy-paste or whether your structure absorbs the change in one place. The right instinct is to separate five concerns immediately: the card model, hand evaluation, category ordering, the game runner, and the log.
Design Decisions Up Front
Category ordering. Represent categories as an enum (or equivalent) with an explicit integer priority. Comparison of two hands then reduces to: compare priorities first; if equal, compare tie-breaker values. Adding a flush between existing categories is just inserting a new enum member with the right priority — no if/else chains to touch.
Tie-breaking. Within a category, produce a tuple of ranks in significance order: for three of a kind it's (triple_rank,); for a pair it's (pair_rank, kicker_rank); for high card it's (card1, card2, card3) descending. Comparing tuples lexicographically is deterministic and requires no special-case code.
The log. Accept a log list as a running accumulation, or return it alongside the result. The key is that game events — hand evaluated, hand discarded, winner declared — are appended as structured records, not printed. This makes the log testable.
Discard rule. Pass it as a callable (or a strategy object) into the game runner. The runner calls it before comparison; it returns a boolean. Swapping it means passing a different callable.
Python Implementation
from enum import Enum
from dataclasses import dataclass, field
from typing import Optional, Callable
# --- Card model ---
@dataclass(frozen=True)
class Card:
rank: int # 2–13; 11=J, 12=Q, 13=K
suit: str # e.g. "hearts", "spades"
# --- Category ordering (insert flush between existing entries safely) ---
class Category(Enum):
HIGH_CARD = 1
PAIR = 2
FLUSH = 3 # Part 2: inserted without touching other entries
THREE_OF_A_KIND = 4
# --- Hand model ---
@dataclass
class Hand:
player: str
cards: list[Card]
category: Optional[Category] = field(default=None, init=False)
tiebreak: tuple = field(default_factory=tuple, init=False)
# --- Evaluation ---
def evaluate(hand: Hand) -> None:
"""Assign category and tiebreak tuple to a hand in place."""
ranks = sorted((c.rank for c in hand.cards), reverse=True)
suits = [c.suit for c in hand.cards]
counts = {}
for r in ranks:
counts[r] = counts.get(r, 0) + 1
if 3 in counts.values():
triple_rank = next(r for r, c in counts.items() if c == 3)
hand.category = Category.THREE_OF_A_KIND
hand.tiebreak = (triple_rank,)
elif 2 in counts.values():
pair_rank = next(r for r, c in counts.items() if c == 2)
kicker_rank = next(r for r, c in counts.items() if c == 1)
hand.category = Category.PAIR
hand.tiebreak = (pair_rank, kicker_rank)
elif len(set(suits)) == 1: # Part 2: flush check
hand.category = Category.FLUSH
hand.tiebreak = tuple(ranks) # highest card first
else:
hand.category = Category.HIGH_CARD
hand.tiebreak = tuple(ranks)
# --- Comparison ---
def hand_key(hand: Hand) -> tuple:
"""Sort key: higher is better."""
return (hand.category.value, hand.tiebreak)
# --- Discard rules (Part 3) ---
def discard_if_not_pair(hand: Hand) -> bool:
"""Return True if the hand should be discarded."""
return hand.category != Category.PAIR # strictly pair only; flush and trips are out
# --- Game runner ---
def play_game(
hands: list[Hand],
discard_rule: Optional[Callable[[Hand], bool]] = None,
) -> tuple[Optional[str], list[dict]]:
"""
Evaluate hands, apply optional discard rule, find winner.
Returns (winner_player_name_or_None, log_list).
"""
log: list[dict] = []
# Evaluate
for hand in hands:
evaluate(hand)
log.append({
"event": "evaluated",
"player": hand.player,
"category": hand.category.name,
"tiebreak": hand.tiebreak,
})
# Discard
active = hands
if discard_rule is not None:
remaining = []
for hand in hands:
if discard_rule(hand):
log.append({"event": "discarded", "player": hand.player,
"reason": "failed discard rule"})
else:
remaining.append(hand)
active = remaining
# Edge cases
if not active:
log.append({"event": "result", "winner": None, "reason": "all hands discarded"})
return None, log
if len(active) == 1:
winner = active[0].player
log.append({"event": "result", "winner": winner, "reason": "sole survivor"})
return winner, log
# Compare
best = max(active, key=hand_key)
top_score = hand_key(best)
tied = [h for h in active if hand_key(h) == top_score]
if len(tied) > 1:
log.append({"event": "result", "winner": None,
"reason": "tie", "players": [h.player for h in tied]})
return None, log
log.append({"event": "result", "winner": best.player})
return best.player, log
Walkthrough of Each Part
Part 1. evaluate handles three of a kind, pair, high card. play_game with discard_rule=None runs a full game. All tie-breaking is done by sorting rank tuples, so no case-specific comparison code exists.
Part 2. The flush branch is inserted into evaluate after the pair check and before the high-card fallback. The Category enum gets one new member at value 3, which slots between PAIR and THREE_OF_A_KIND automatically. Nothing else changes.
Part 3. discard_if_not_pair is passed in at call time: play_game(hands, discard_rule=discard_if_not_pair). Swapping it later means passing a different function — the runner is untouched. The function as written discards everything except strictly PAIR, so flush and three of a kind hands are eliminated. If the rule changes (say, "discard if not pair or better"), you write a new one-liner.
Complexity
Evaluating a hand of k cards is O(k). Ranking n hands is O(n · k). For any realistic game size, this is negligible — the interesting complexity is in the design, not the algorithm.
Common Mistakes
- Encoding priority in comparison logic rather than in the enum. Leads to a chain of
if category == 'flush' and other_category == 'pair'comparisons that breaks every time a category is added. - Printing the log instead of returning it. Makes the game untestable and breaks the contract.
- Hardcoding the discard rule inside hand evaluation or the comparison step, rather than treating it as a pre-processing pass. This conflates filtering with ranking.
- Forgetting the "all discarded" edge case — the runner must handle it explicitly, and the log must record it.