Skip to main content

native_solver/
eval.rs

1//! Poker hand strength: [`evaluate_5`] for exactly five cards and
2//! [`evaluate_7`] for the best five of seven (two hole cards and a board).
3//!
4//! Both return a [`HandStrength`]; stronger hands compare greater, and equal
5//! strengths split the pot.
6//!
7//! ```
8//! use native_solver::{evaluate_7, Card, HandCategory};
9//!
10//! let cards = |s: &str| -> Vec<Card> { s.split(' ').map(|c| c.parse().unwrap()).collect() };
11//! let board = cards("Ks Th 7s 4d 2s");
12//! let hand = |hole: &str| {
13//!     let all: Vec<Card> = cards(hole).into_iter().chain(board.iter().copied()).collect();
14//!     evaluate_7(all.try_into().unwrap())
15//! };
16//! assert!(hand("As 9s") > hand("Kd Kc")); // a flush beats a set
17//! assert_eq!(hand("As 9s").category(), HandCategory::Flush);
18//! ```
19
20// Implementation notes.
21//
22// `evaluate_5` is table-driven for speed, since CFR calls it an enormous
23// number of times. Every 5-card hand falls into one of two cases:
24//
25// - **All 5 ranks distinct**: straight/flush/high-card only (a repeated
26//   rank is impossible here, so no pair-or-better). Which of the 13
27//   ranks are present is a 13-bit bitmask (0..8192); `TABLES.straight_high`
28//   and `TABLES.high_card_tiebreak`, precomputed once and indexed directly
29//   by that bitmask, give the answer with no branching or sorting.
30// - **A rank repeats**: pair or better. Two cards can never share both
31//   rank and suit, so a repeated rank makes a flush structurally
32//   impossible — the hand's category is fully determined by the
33//   *multiset* of ranks alone. Assigning each rank a distinct prime and
34//   multiplying the 5 cards' primes gives a product that's unique per
35//   multiset (unique prime factorization), so `TABLES.paired` (keyed by
36//   that product) looks the score up directly.
37//
38// Both tables are built once, lazily, from `evaluate_5_reference` — the
39// original correctness-first implementation (grouping + sorting, checked
40// all 21 5-card subsets' worth of hand types by hand in earlier
41// milestones) — kept around purely as the oracle for table generation and
42// for the exhaustive cross-check test below. `evaluate_5` and
43// `evaluate_5_reference` are checked equal across all C(52,5) = 2,598,960
44// possible 5-card hands, not just a handful of examples.
45
46use crate::card::Card;
47use std::collections::HashMap;
48use std::sync::OnceLock;
49
50const CAT_HIGH_CARD: u32 = 0;
51const CAT_PAIR: u32 = 1;
52const CAT_TWO_PAIR: u32 = 2;
53const CAT_THREE_KIND: u32 = 3;
54const CAT_STRAIGHT: u32 = 4;
55const CAT_FLUSH: u32 = 5;
56const CAT_FULL_HOUSE: u32 = 6;
57const CAT_FOUR_KIND: u32 = 7;
58const CAT_STRAIGHT_FLUSH: u32 = 8;
59
60/// Hand categories, ordered from weakest to strongest.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub enum HandCategory {
63    /// No pair or better.
64    HighCard,
65    /// One pair.
66    Pair,
67    /// Two pairs.
68    TwoPair,
69    /// Three cards of one rank.
70    ThreeOfAKind,
71    /// Five consecutive ranks, including the ace-low wheel.
72    Straight,
73    /// Five cards of one suit.
74    Flush,
75    /// Three of one rank and a pair of another.
76    FullHouse,
77    /// Four cards of one rank.
78    FourOfAKind,
79    /// A straight in one suit, including the royal flush.
80    StraightFlush,
81}
82
83/// The strength of a five-card poker hand; stronger hands compare greater.
84///
85/// [`evaluate_5`] and [`evaluate_7`] return it. Equal strengths split the
86/// pot.
87///
88/// ```
89/// use native_solver::{evaluate_5, Card, HandCategory};
90///
91/// let hand = |s: &str| -> [Card; 5] {
92///     let cards: Vec<Card> = s.split(' ').map(|c| c.parse().unwrap()).collect();
93///     cards.try_into().unwrap()
94/// };
95/// let flush = evaluate_5(hand("Ah 9h 7h 4h 2h"));
96/// let straight = evaluate_5(hand("9h 8d 7s 6h 5c"));
97/// assert!(flush > straight);
98/// assert_eq!(flush.category(), HandCategory::Flush);
99/// ```
100#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
101pub struct HandStrength(pub(crate) u32);
102
103impl HandStrength {
104    /// The hand's category, e.g. [`HandCategory::Flush`].
105    pub fn category(self) -> HandCategory {
106        category_of(self.0)
107    }
108}
109
110/// The category packed into the top bits of an internal score.
111fn category_of(score: u32) -> HandCategory {
112    match score >> 20 {
113        CAT_HIGH_CARD => HandCategory::HighCard,
114        CAT_PAIR => HandCategory::Pair,
115        CAT_TWO_PAIR => HandCategory::TwoPair,
116        CAT_THREE_KIND => HandCategory::ThreeOfAKind,
117        CAT_STRAIGHT => HandCategory::Straight,
118        CAT_FLUSH => HandCategory::Flush,
119        CAT_FULL_HOUSE => HandCategory::FullHouse,
120        CAT_FOUR_KIND => HandCategory::FourOfAKind,
121        CAT_STRAIGHT_FLUSH => HandCategory::StraightFlush,
122        other => unreachable!("invalid hand category bits: {other}"),
123    }
124}
125
126/// Pack up to 5 tiebreak ranks (most significant first) into the low 20
127/// bits of a score, in the same bit positions `pack` uses.
128fn pack_ranks(ranks: &[u8]) -> u32 {
129    let mut bits = 0u32;
130    for (i, &r) in ranks.iter().enumerate() {
131        bits |= (r as u32) << (16 - i * 4);
132    }
133    bits
134}
135
136/// Pack a category and up to 5 tiebreak ranks (most significant first) into
137/// a single comparable score: higher score always beats lower score.
138fn pack(category: u32, ranks: &[u8]) -> u32 {
139    (category << 20) | pack_ranks(ranks)
140}
141
142/// Ranks (descending, unique) that make up a straight, if any. `ranks_desc`
143/// must already be sorted descending and deduplicated.
144fn straight_high(ranks_desc: &[u8]) -> Option<u8> {
145    if ranks_desc.len() != 5 {
146        return None;
147    }
148    // Wheel: A-2-3-4-5, i.e. rank indices 12,3,2,1,0. High card is the "5" (index 3).
149    if ranks_desc == [12, 3, 2, 1, 0] {
150        return Some(3);
151    }
152    for w in ranks_desc.windows(2) {
153        if w[0] != w[1] + 1 {
154            return None;
155        }
156    }
157    Some(ranks_desc[0])
158}
159
160/// Slow, case-by-case [`evaluate_5`], kept as a test and benchmark oracle.
161///
162/// Not part of the documented API; it may change without notice.
163#[doc(hidden)]
164pub fn evaluate_5_reference(cards: [Card; 5]) -> u32 {
165    let mut rank_counts = [0u8; 13];
166    let mut suit_counts = [0u8; 4];
167    for &c in &cards {
168        rank_counts[c.rank() as usize] += 1;
169        suit_counts[c.suit() as usize] += 1;
170    }
171    let is_flush = suit_counts.contains(&5);
172
173    let mut ranks_desc: Vec<u8> = (0..13u8).filter(|&r| rank_counts[r as usize] > 0).collect();
174    ranks_desc.sort_unstable_by(|a, b| b.cmp(a));
175    let straight = straight_high(&ranks_desc);
176
177    if is_flush {
178        if let Some(high) = straight {
179            return pack(CAT_STRAIGHT_FLUSH, &[high]);
180        }
181    }
182
183    let mut groups: Vec<(u8, u8)> = (0..13u8)
184        .filter(|&r| rank_counts[r as usize] > 0)
185        .map(|r| (rank_counts[r as usize], r))
186        .collect();
187    groups.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
188
189    match groups[0].0 {
190        4 => pack(CAT_FOUR_KIND, &[groups[0].1, groups[1].1]),
191        3 if groups[1].0 >= 2 => pack(CAT_FULL_HOUSE, &[groups[0].1, groups[1].1]),
192        3 => pack(CAT_THREE_KIND, &[groups[0].1, groups[1].1, groups[2].1]),
193        2 if groups[1].0 == 2 => pack(CAT_TWO_PAIR, &[groups[0].1, groups[1].1, groups[2].1]),
194        2 => pack(
195            CAT_PAIR,
196            &[groups[0].1, groups[1].1, groups[2].1, groups[3].1],
197        ),
198        _ if is_flush => {
199            let ranks: Vec<u8> = groups.iter().map(|g| g.1).collect();
200            pack(CAT_FLUSH, &ranks)
201        }
202        _ if straight.is_some() => pack(CAT_STRAIGHT, &[straight.unwrap()]),
203        _ => {
204            let ranks: Vec<u8> = groups.iter().map(|g| g.1).collect();
205            pack(CAT_HIGH_CARD, &ranks)
206        }
207    }
208}
209
210/// One prime per rank (2..=A); the product of a 5-card hand's rank primes
211/// is unique per rank *multiset* (unique prime factorization), so it's a
212/// perfect key for the paired-hand lookup table.
213const RANK_PRIMES: [u64; 13] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
214
215struct Tables {
216    /// Indexed by the 13-bit "which ranks are present" bitmask (only
217    /// entries with exactly 5 bits set are meaningful): `Some(high)` if
218    /// those 5 ranks form a straight.
219    straight_high: Vec<Option<u8>>,
220    /// Same indexing; packed tiebreak ranks for the non-straight case
221    /// (used for both flush and high-card, which share the same ordering).
222    high_card_tiebreak: Vec<u32>,
223    /// Rank-prime product -> full packed score, for every 5-rank multiset
224    /// that has at least one repeat (pair or better). A repeated rank
225    /// makes a flush structurally impossible, so the category is fully
226    /// determined by the multiset alone.
227    paired: HashMap<u64, u32>,
228}
229
230static TABLES: OnceLock<Tables> = OnceLock::new();
231
232fn tables() -> &'static Tables {
233    TABLES.get_or_init(build_tables)
234}
235
236fn build_tables() -> Tables {
237    let mut straight_high_table = vec![None; 8192];
238    let mut high_card_tiebreak = vec![0u32; 8192];
239    for mask in 0u16..8192 {
240        if mask.count_ones() != 5 {
241            continue;
242        }
243        let ranks_desc: Vec<u8> = (0..13u8).rev().filter(|&r| mask & (1 << r) != 0).collect();
244        straight_high_table[mask as usize] = straight_high(&ranks_desc);
245        high_card_tiebreak[mask as usize] = pack_ranks(&ranks_desc);
246    }
247
248    let mut paired = HashMap::new();
249    for ranks in rank_multisets_with_repeat() {
250        let hand = representative_hand(&ranks);
251        let score = evaluate_5_reference(hand);
252        let product: u64 = ranks.iter().map(|&r| RANK_PRIMES[r as usize]).product();
253        paired.insert(product, score);
254    }
255
256    Tables {
257        straight_high: straight_high_table,
258        high_card_tiebreak,
259        paired,
260    }
261}
262
263/// Every non-increasing sequence of 5 ranks (0..13) with at least one
264/// repeated value — i.e. every possible 5-card rank multiset that isn't
265/// all-distinct (and excluding 5-of-a-kind, which is impossible with only
266/// 4 suits per rank). There are C(17,5) - C(13,5) - 13 = 6188 - 1287 - 13
267/// = 4888 of them.
268fn rank_multisets_with_repeat() -> Vec<[u8; 5]> {
269    let mut out = Vec::new();
270    for r0 in 0..13u8 {
271        for r1 in 0..=r0 {
272            for r2 in 0..=r1 {
273                for r3 in 0..=r2 {
274                    for r4 in 0..=r3 {
275                        let ranks = [r0, r1, r2, r3, r4];
276                        let mut counts = [0u8; 13];
277                        for &r in &ranks {
278                            counts[r as usize] += 1;
279                        }
280                        let max_count = counts.iter().copied().max().unwrap();
281                        if (2..=4).contains(&max_count) {
282                            out.push(ranks);
283                        }
284                    }
285                }
286            }
287        }
288    }
289    out
290}
291
292/// A concrete 5-card hand with the given ranks (assigning increasing
293/// suits to repeats of the same rank, which never collides since a rank
294/// repeats at most 4 times).
295fn representative_hand(ranks: &[u8; 5]) -> [Card; 5] {
296    let mut next_suit = [0u8; 13];
297    let mut cards = [Card(0); 5];
298    for (i, &r) in ranks.iter().enumerate() {
299        let s = next_suit[r as usize];
300        next_suit[r as usize] += 1;
301        cards[i] = Card(r * 4 + s);
302    }
303    cards
304}
305
306/// The strength of an exact five-card hand.
307///
308/// The five cards must be distinct; repeated cards give a meaningless
309/// result and may panic.
310pub fn evaluate_5(cards: [Card; 5]) -> HandStrength {
311    HandStrength(score_5(cards))
312}
313
314/// [`evaluate_5`] as a raw score, for the solver's hot paths.
315pub(crate) fn score_5(cards: [Card; 5]) -> u32 {
316    debug_assert!(
317        crate::card::CardSet::from_cards(&cards).len() == 5,
318        "evaluate_5 needs five distinct cards"
319    );
320    let t = tables();
321
322    let mut suit_counts = [0u8; 4];
323    let mut rank_mask: u16 = 0;
324    let mut has_repeat = false;
325    for &c in &cards {
326        let r = c.rank();
327        suit_counts[c.suit() as usize] += 1;
328        let bit = 1u16 << r;
329        if rank_mask & bit != 0 {
330            has_repeat = true;
331        }
332        rank_mask |= bit;
333    }
334    let is_flush = suit_counts.contains(&5);
335
336    if !has_repeat {
337        if let Some(high) = t.straight_high[rank_mask as usize] {
338            let cat = if is_flush {
339                CAT_STRAIGHT_FLUSH
340            } else {
341                CAT_STRAIGHT
342            };
343            return pack(cat, &[high]);
344        }
345        let cat = if is_flush { CAT_FLUSH } else { CAT_HIGH_CARD };
346        return (cat << 20) | t.high_card_tiebreak[rank_mask as usize];
347    }
348
349    let product: u64 = cards
350        .iter()
351        .map(|&c| RANK_PRIMES[c.rank() as usize])
352        .product();
353    *t.paired
354        .get(&product)
355        .expect("every 5-card rank multiset is precomputed in `paired`")
356}
357
358/// All 21 ways to choose 5 indices out of 7.
359#[cfg(test)]
360const COMBOS_7_CHOOSE_5: [[usize; 5]; 21] = [
361    [0, 1, 2, 3, 4],
362    [0, 1, 2, 3, 5],
363    [0, 1, 2, 3, 6],
364    [0, 1, 2, 4, 5],
365    [0, 1, 2, 4, 6],
366    [0, 1, 2, 5, 6],
367    [0, 1, 3, 4, 5],
368    [0, 1, 3, 4, 6],
369    [0, 1, 3, 5, 6],
370    [0, 1, 4, 5, 6],
371    [0, 2, 3, 4, 5],
372    [0, 2, 3, 4, 6],
373    [0, 2, 3, 5, 6],
374    [0, 2, 4, 5, 6],
375    [0, 3, 4, 5, 6],
376    [1, 2, 3, 4, 5],
377    [1, 2, 3, 4, 6],
378    [1, 2, 3, 5, 6],
379    [1, 2, 4, 5, 6],
380    [1, 3, 4, 5, 6],
381    [2, 3, 4, 5, 6],
382];
383
384/// The strength of the best five-card hand out of seven cards, e.g. two hole
385/// cards and a five-card board.
386///
387/// The seven cards must be distinct; repeated cards give a meaningless
388/// result and may panic.
389pub fn evaluate_7(cards: [Card; 7]) -> HandStrength {
390    HandStrength(score_7(cards))
391}
392
393/// The highest set bit of a non-empty 13-bit rank mask, as a rank.
394fn top_rank(mask: u16) -> u32 {
395    15 - mask.leading_zeros()
396}
397
398/// Packs the `count` highest ranks of `mask`, highest first, starting at
399/// nibble `first` of the tiebreak (nibble 0 is the most significant).
400fn pack_top_ranks(mut mask: u16, count: usize, first: usize) -> u32 {
401    let mut bits = 0;
402    for i in first..first + count {
403        let rank = top_rank(mask);
404        bits |= rank << (16 - i * 4);
405        mask &= !(1 << rank);
406    }
407    bits
408}
409
410/// The high card of the best straight among the ranks of `mask`, if any.
411/// The wheel (A-2-3-4-5) counts as five-high.
412fn best_straight_high(mask: u16) -> Option<u32> {
413    // Bit 0 is the ace playing low; rank `r` sits at bit `r + 1`.
414    let low_ace = (mask << 1) | (mask >> 12 & 1);
415    let runs = low_ace & low_ace >> 1 & low_ace >> 2 & low_ace >> 3 & low_ace >> 4;
416    // A run starting at bit `i` ends on rank `i + 3`.
417    (runs != 0).then(|| top_rank(runs) + 3)
418}
419
420/// [`evaluate_7`] as a raw score, for the solver's hot paths.
421///
422/// Reads the best five-card hand directly from rank and suit counts. Equal to
423/// the maximum of [`score_5`] over all 21 five-card subsets.
424pub(crate) fn score_7(cards: [Card; 7]) -> u32 {
425    let mut suits = [0u16; 4];
426    // Ranks held at least once, twice, three and four times.
427    let (mut any, mut pairs, mut trips, mut quads) = (0u16, 0u16, 0u16, 0u16);
428    for card in cards {
429        let bit = 1u16 << card.rank();
430        suits[card.suit() as usize] |= bit;
431        quads |= trips & bit;
432        trips |= pairs & bit;
433        pairs |= any & bit;
434        any |= bit;
435    }
436
437    // Five cards of one suit leave room for at most one more card of any of
438    // their ranks plus one other, so a flush rules out quads and full houses.
439    for flush in suits {
440        if flush.count_ones() >= 5 {
441            return match best_straight_high(flush) {
442                Some(high) => (CAT_STRAIGHT_FLUSH << 20) | (high << 16),
443                None => (CAT_FLUSH << 20) | pack_top_ranks(flush, 5, 0),
444            };
445        }
446    }
447    if quads != 0 {
448        let quad = top_rank(quads);
449        return (CAT_FOUR_KIND << 20) | (quad << 16) | pack_top_ranks(any & !(1 << quad), 1, 1);
450    }
451    if trips != 0 {
452        let trip = top_rank(trips);
453        let others = pairs & !(1 << trip);
454        if others != 0 {
455            return (CAT_FULL_HOUSE << 20) | (trip << 16) | (top_rank(others) << 12);
456        }
457    }
458    if let Some(high) = best_straight_high(any) {
459        return (CAT_STRAIGHT << 20) | (high << 16);
460    }
461    if trips != 0 {
462        let trip = top_rank(trips);
463        return (CAT_THREE_KIND << 20) | (trip << 16) | pack_top_ranks(any & !(1 << trip), 2, 1);
464    }
465    if pairs != 0 {
466        let high = top_rank(pairs);
467        let lower = pairs & !(1 << high);
468        if lower != 0 {
469            let low = top_rank(lower);
470            let kickers = any & !(1 << high) & !(1 << low);
471            return (CAT_TWO_PAIR << 20)
472                | (high << 16)
473                | (low << 12)
474                | pack_top_ranks(kickers, 1, 2);
475        }
476        return (CAT_PAIR << 20) | (high << 16) | pack_top_ranks(any & !(1 << high), 3, 1);
477    }
478    (CAT_HIGH_CARD << 20) | pack_top_ranks(any, 5, 0)
479}
480
481/// [`score_7`] as originally defined: the best of all 21 five-card subsets.
482#[cfg(test)]
483fn score_7_reference(cards: [Card; 7]) -> u32 {
484    COMBOS_7_CHOOSE_5
485        .iter()
486        .map(|combo| {
487            let five = [
488                cards[combo[0]],
489                cards[combo[1]],
490                cards[combo[2]],
491                cards[combo[3]],
492                cards[combo[4]],
493            ];
494            score_5(five)
495        })
496        .max()
497        .expect("21 combos is never empty")
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503    use crate::card::Card;
504
505    fn hand5(cards: &str) -> [Card; 5] {
506        let parsed: Vec<Card> = cards
507            .split_whitespace()
508            .map(|c| c.parse::<Card>().unwrap())
509            .collect();
510        parsed.try_into().unwrap()
511    }
512
513    fn hand7(cards: &str) -> [Card; 7] {
514        let parsed: Vec<Card> = cards
515            .split_whitespace()
516            .map(|c| c.parse::<Card>().unwrap())
517            .collect();
518        parsed.try_into().unwrap()
519    }
520
521    /// Visits every 7-card hand whose lowest card index is `offset`, or
522    /// `offset` plus a multiple of `stride`.
523    fn for_each_7_card_hand(stride: u8, offset: u8, mut visit: impl FnMut([Card; 7])) {
524        for a in (offset..52).step_by(stride as usize) {
525            for b in a + 1..52 {
526                for c in b + 1..52 {
527                    for d in c + 1..52 {
528                        for e in d + 1..52 {
529                            for f in e + 1..52 {
530                                for g in f + 1..52 {
531                                    visit([a, b, c, d, e, f, g].map(Card));
532                                }
533                            }
534                        }
535                    }
536                }
537            }
538        }
539    }
540
541    #[test]
542    fn evaluate_7_matches_best_of_21_on_a_sample() {
543        // Every 61st hand of the full enumeration: about two million.
544        let (mut index, mut checked) = (0u32, 0u32);
545        for offset in 0..46 {
546            for_each_7_card_hand(52, offset, |hand| {
547                if index % 61 == 0 {
548                    assert_eq!(score_7(hand), score_7_reference(hand), "{hand:?}");
549                    checked += 1;
550                }
551                index += 1;
552            });
553        }
554        assert_eq!(index, 133_784_560);
555        assert_eq!(checked, 2_193_190);
556    }
557
558    #[test]
559    fn evaluate_7_does_not_depend_on_card_order() {
560        let hand = hand7("As Ah Kd Kc 7s 7d 2c");
561        let expected = score_7_reference(hand);
562        let mut rotated = hand;
563        for _ in 0..7 {
564            rotated.rotate_left(1);
565            assert_eq!(score_7(rotated), expected);
566            let mut swapped = rotated;
567            swapped.swap(0, 4);
568            assert_eq!(score_7(swapped), expected);
569        }
570    }
571
572    /// All 133,784,560 hands; about a minute of CPU time. Run with
573    /// `cargo test --release evaluate_7_matches_best_of_21_for_every_hand -- --ignored`.
574    #[test]
575    #[ignore = "exhaustive: about a minute of CPU time"]
576    fn evaluate_7_matches_best_of_21_for_every_hand() {
577        use rayon::prelude::*;
578        let hands: u64 = (0u8..46)
579            .into_par_iter()
580            .map(|offset| {
581                let mut hands = 0u64;
582                for_each_7_card_hand(52, offset, |hand| {
583                    assert_eq!(score_7(hand), score_7_reference(hand), "{hand:?}");
584                    hands += 1;
585                });
586                hands
587            })
588            .sum();
589        assert_eq!(hands, 133_784_560);
590    }
591
592    #[test]
593    fn categorizes_each_hand_type() {
594        assert_eq!(
595            evaluate_5(hand5("As Ks Qs Js Ts")).category(),
596            HandCategory::StraightFlush
597        );
598        assert_eq!(
599            evaluate_5(hand5("5s 4s 3s 2s As")).category(),
600            HandCategory::StraightFlush
601        ); // wheel
602        assert_eq!(
603            evaluate_5(hand5("Ah Ad As Ac Kh")).category(),
604            HandCategory::FourOfAKind
605        );
606        assert_eq!(
607            evaluate_5(hand5("Ah Ad As Kh Kd")).category(),
608            HandCategory::FullHouse
609        );
610        assert_eq!(
611            evaluate_5(hand5("Ah 9h 7h 4h 2h")).category(),
612            HandCategory::Flush
613        );
614        assert_eq!(
615            evaluate_5(hand5("9h 8d 7s 6h 5c")).category(),
616            HandCategory::Straight
617        );
618        assert_eq!(
619            evaluate_5(hand5("Ah Ad As Kh Qd")).category(),
620            HandCategory::ThreeOfAKind
621        );
622        assert_eq!(
623            evaluate_5(hand5("Ah Ad Kh Kd Qc")).category(),
624            HandCategory::TwoPair
625        );
626        assert_eq!(
627            evaluate_5(hand5("Ah Ad Kh Qd Jc")).category(),
628            HandCategory::Pair
629        );
630        assert_eq!(
631            evaluate_5(hand5("Ah Kd Qh Jd 9c")).category(),
632            HandCategory::HighCard
633        );
634    }
635
636    #[test]
637    fn wheel_straight_loses_to_six_high_straight() {
638        let wheel = evaluate_5(hand5("5s 4s 3d 2c As"));
639        let six_high = evaluate_5(hand5("6s 5d 4d 3c 2h"));
640        assert!(six_high > wheel);
641    }
642
643    #[test]
644    fn higher_trips_beats_lower_trips_in_full_house() {
645        let aces_full = evaluate_5(hand5("Ah Ad As Kh Kd"));
646        let kings_full = evaluate_5(hand5("Kh Kd Ks Ah Ad"));
647        assert!(aces_full > kings_full);
648    }
649
650    #[test]
651    fn flush_beats_straight_beats_trips() {
652        let flush = evaluate_5(hand5("Ah 9h 7h 4h 2h"));
653        let straight = evaluate_5(hand5("9h 8d 7s 6h 5c"));
654        let trips = evaluate_5(hand5("Ah Ad As Kh Qd"));
655        assert!(flush > straight);
656        assert!(straight > trips);
657    }
658
659    #[test]
660    fn evaluate_7_picks_best_two_pair_from_three_pairs() {
661        // Board AA KK QQ, hole cards 2 3: best hand should be AAKKQ (top two pair), not AAQQ or KKQQ.
662        let best = evaluate_7(hand7("2c 3d Ah Ad Kh Kd Qh"));
663        let expected = evaluate_5(hand5("Ah Ad Kh Kd Qh"));
664        assert_eq!(best, expected);
665        assert_eq!(best.category(), HandCategory::TwoPair);
666    }
667
668    #[test]
669    fn evaluate_7_finds_straight_using_board_and_hole_cards() {
670        // Hole: 9h 8d, board: 7s 6h 5c 2d 2s -> best is 9-high straight.
671        let best = evaluate_7(hand7("9h 8d 7s 6h 5c 2d 2s"));
672        assert_eq!(best.category(), HandCategory::Straight);
673        let expected = evaluate_5(hand5("9h 8d 7s 6h 5c"));
674        assert_eq!(best, expected);
675    }
676
677    /// Cross-checks the table-driven `evaluate_5` against the original
678    /// grouping-based `evaluate_5_reference` for every one of the
679    /// C(52,5) = 2,598,960 possible 5-card hands — not just a handful of
680    /// hand-picked examples.
681    #[test]
682    fn evaluate_5_matches_reference_for_every_possible_hand() {
683        let mut checked = 0u64;
684        for a in 0u8..52 {
685            for b in (a + 1)..52 {
686                for c in (b + 1)..52 {
687                    for d in (c + 1)..52 {
688                        for e in (d + 1)..52 {
689                            let hand = [a, b, c, d, e].map(Card);
690                            let fast = score_5(hand);
691                            let reference = evaluate_5_reference(hand);
692                            assert_eq!(fast, reference, "mismatch for hand {hand:?}");
693                            checked += 1;
694                        }
695                    }
696                }
697            }
698        }
699        assert_eq!(checked, 2_598_960);
700    }
701}