KatInterview

Expected Matching-Rank Pairs in a Random Card Hand

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilityexpectationcombinatorics

Last updated

Compute the expected number of same-rank card pairs in a hand drawn without replacement, using linearity of expectation over pairs of cards.

Matching Ranks in a Random Hand

A deck is made of ranks different ranks, and each rank has copies physically distinct cards. The deck therefore holds ranks * copies cards. The deck is shuffled and a hand of hand_size cards is dealt from it without replacement, so every subset of hand_size cards is equally likely.

A pair is any unordered set of two cards in the hand that have the same rank. Pairs are counted over all combinations of cards, so:

  • a rank appearing 2 times in the hand contributes 1 pair,
  • a rank appearing 3 times contributes 3 pairs,
  • a rank appearing 4 times contributes 6 pairs,

and in general a rank appearing c times contributes c * (c - 1) / 2 pairs.

Write a function that returns the expected number of pairs in the dealt hand, as a floating-point number.

Input

  • ranks: number of distinct ranks.
  • copies: number of cards of each rank.
  • hand_size: number of cards dealt.

Output

A float equal to the expected number of same-rank pairs in the hand. Return 0.0 when the hand cannot contain any pair (fewer than 2 cards dealt, or fewer than 2 cards in the whole deck).

Constraints

  • ranks, copies and hand_size are positive integers.
  • hand_size <= ranks * copies.
  • Every set of hand_size cards is equally likely.
  • Results are compared as floating-point values, so use the exact formula rather than a simulation.

Examples

Example 1

Input: expected_matching_pairs(13, 4, 5)

Output: 0.5882352941176471

Example 2

Input: expected_matching_pairs(4, 2, 3)

Output: 0.42857142857142855

Example 3

Input: expected_matching_pairs(2, 5, 7)

Output: 9.333333333333334

Hints

Hint 1

Write the pair count as a sum of indicator variables, one for each unordered pair of cards in the whole deck: the indicator is 1 when both cards land in the hand and share a rank.

Hint 2

For a fixed two cards, the chance both are in the hand is hand_size*(hand_size-1) / (D*(D-1)), where D is the deck size. Linearity of expectation means you do not need independence between indicators.

Hint 3

Count how many same-rank card pairs exist in the full deck: ranks * C(copies, 2). Multiply by the probability from the previous hint.