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.
359const COMBOS_7_CHOOSE_5: [[usize; 5]; 21] = [
360    [0, 1, 2, 3, 4],
361    [0, 1, 2, 3, 5],
362    [0, 1, 2, 3, 6],
363    [0, 1, 2, 4, 5],
364    [0, 1, 2, 4, 6],
365    [0, 1, 2, 5, 6],
366    [0, 1, 3, 4, 5],
367    [0, 1, 3, 4, 6],
368    [0, 1, 3, 5, 6],
369    [0, 1, 4, 5, 6],
370    [0, 2, 3, 4, 5],
371    [0, 2, 3, 4, 6],
372    [0, 2, 3, 5, 6],
373    [0, 2, 4, 5, 6],
374    [0, 3, 4, 5, 6],
375    [1, 2, 3, 4, 5],
376    [1, 2, 3, 4, 6],
377    [1, 2, 3, 5, 6],
378    [1, 2, 4, 5, 6],
379    [1, 3, 4, 5, 6],
380    [2, 3, 4, 5, 6],
381];
382
383/// The strength of the best five-card hand out of seven cards, e.g. two hole
384/// cards and a five-card board.
385///
386/// The seven cards must be distinct; repeated cards give a meaningless
387/// result and may panic.
388pub fn evaluate_7(cards: [Card; 7]) -> HandStrength {
389    HandStrength(score_7(cards))
390}
391
392/// [`evaluate_7`] as a raw score, for the solver's hot paths.
393pub(crate) fn score_7(cards: [Card; 7]) -> u32 {
394    COMBOS_7_CHOOSE_5
395        .iter()
396        .map(|combo| {
397            let five = [
398                cards[combo[0]],
399                cards[combo[1]],
400                cards[combo[2]],
401                cards[combo[3]],
402                cards[combo[4]],
403            ];
404            score_5(five)
405        })
406        .max()
407        .expect("21 combos is never empty")
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413    use crate::card::Card;
414
415    fn hand5(cards: &str) -> [Card; 5] {
416        let parsed: Vec<Card> = cards
417            .split_whitespace()
418            .map(|c| c.parse::<Card>().unwrap())
419            .collect();
420        parsed.try_into().unwrap()
421    }
422
423    fn hand7(cards: &str) -> [Card; 7] {
424        let parsed: Vec<Card> = cards
425            .split_whitespace()
426            .map(|c| c.parse::<Card>().unwrap())
427            .collect();
428        parsed.try_into().unwrap()
429    }
430
431    #[test]
432    fn categorizes_each_hand_type() {
433        assert_eq!(
434            evaluate_5(hand5("As Ks Qs Js Ts")).category(),
435            HandCategory::StraightFlush
436        );
437        assert_eq!(
438            evaluate_5(hand5("5s 4s 3s 2s As")).category(),
439            HandCategory::StraightFlush
440        ); // wheel
441        assert_eq!(
442            evaluate_5(hand5("Ah Ad As Ac Kh")).category(),
443            HandCategory::FourOfAKind
444        );
445        assert_eq!(
446            evaluate_5(hand5("Ah Ad As Kh Kd")).category(),
447            HandCategory::FullHouse
448        );
449        assert_eq!(
450            evaluate_5(hand5("Ah 9h 7h 4h 2h")).category(),
451            HandCategory::Flush
452        );
453        assert_eq!(
454            evaluate_5(hand5("9h 8d 7s 6h 5c")).category(),
455            HandCategory::Straight
456        );
457        assert_eq!(
458            evaluate_5(hand5("Ah Ad As Kh Qd")).category(),
459            HandCategory::ThreeOfAKind
460        );
461        assert_eq!(
462            evaluate_5(hand5("Ah Ad Kh Kd Qc")).category(),
463            HandCategory::TwoPair
464        );
465        assert_eq!(
466            evaluate_5(hand5("Ah Ad Kh Qd Jc")).category(),
467            HandCategory::Pair
468        );
469        assert_eq!(
470            evaluate_5(hand5("Ah Kd Qh Jd 9c")).category(),
471            HandCategory::HighCard
472        );
473    }
474
475    #[test]
476    fn wheel_straight_loses_to_six_high_straight() {
477        let wheel = evaluate_5(hand5("5s 4s 3d 2c As"));
478        let six_high = evaluate_5(hand5("6s 5d 4d 3c 2h"));
479        assert!(six_high > wheel);
480    }
481
482    #[test]
483    fn higher_trips_beats_lower_trips_in_full_house() {
484        let aces_full = evaluate_5(hand5("Ah Ad As Kh Kd"));
485        let kings_full = evaluate_5(hand5("Kh Kd Ks Ah Ad"));
486        assert!(aces_full > kings_full);
487    }
488
489    #[test]
490    fn flush_beats_straight_beats_trips() {
491        let flush = evaluate_5(hand5("Ah 9h 7h 4h 2h"));
492        let straight = evaluate_5(hand5("9h 8d 7s 6h 5c"));
493        let trips = evaluate_5(hand5("Ah Ad As Kh Qd"));
494        assert!(flush > straight);
495        assert!(straight > trips);
496    }
497
498    #[test]
499    fn evaluate_7_picks_best_two_pair_from_three_pairs() {
500        // Board AA KK QQ, hole cards 2 3: best hand should be AAKKQ (top two pair), not AAQQ or KKQQ.
501        let best = evaluate_7(hand7("2c 3d Ah Ad Kh Kd Qh"));
502        let expected = evaluate_5(hand5("Ah Ad Kh Kd Qh"));
503        assert_eq!(best, expected);
504        assert_eq!(best.category(), HandCategory::TwoPair);
505    }
506
507    #[test]
508    fn evaluate_7_finds_straight_using_board_and_hole_cards() {
509        // Hole: 9h 8d, board: 7s 6h 5c 2d 2s -> best is 9-high straight.
510        let best = evaluate_7(hand7("9h 8d 7s 6h 5c 2d 2s"));
511        assert_eq!(best.category(), HandCategory::Straight);
512        let expected = evaluate_5(hand5("9h 8d 7s 6h 5c"));
513        assert_eq!(best, expected);
514    }
515
516    /// Cross-checks the table-driven `evaluate_5` against the original
517    /// grouping-based `evaluate_5_reference` for every one of the
518    /// C(52,5) = 2,598,960 possible 5-card hands — not just a handful of
519    /// hand-picked examples.
520    #[test]
521    fn evaluate_5_matches_reference_for_every_possible_hand() {
522        let mut checked = 0u64;
523        for a in 0u8..52 {
524            for b in (a + 1)..52 {
525                for c in (b + 1)..52 {
526                    for d in (c + 1)..52 {
527                        for e in (d + 1)..52 {
528                            let hand = [a, b, c, d, e].map(Card);
529                            let fast = score_5(hand);
530                            let reference = evaluate_5_reference(hand);
531                            assert_eq!(fast, reference, "mismatch for hand {hand:?}");
532                            checked += 1;
533                        }
534                    }
535                }
536            }
537        }
538        assert_eq!(checked, 2_598_960);
539    }
540}