1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub enum HandCategory {
63 HighCard,
65 Pair,
67 TwoPair,
69 ThreeOfAKind,
71 Straight,
73 Flush,
75 FullHouse,
77 FourOfAKind,
79 StraightFlush,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
101pub struct HandStrength(pub(crate) u32);
102
103impl HandStrength {
104 pub fn category(self) -> HandCategory {
106 category_of(self.0)
107 }
108}
109
110fn 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
126fn 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
136fn pack(category: u32, ranks: &[u8]) -> u32 {
139 (category << 20) | pack_ranks(ranks)
140}
141
142fn straight_high(ranks_desc: &[u8]) -> Option<u8> {
145 if ranks_desc.len() != 5 {
146 return None;
147 }
148 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#[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
210const RANK_PRIMES: [u64; 13] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
214
215struct Tables {
216 straight_high: Vec<Option<u8>>,
220 high_card_tiebreak: Vec<u32>,
223 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
263fn 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
292fn 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
306pub fn evaluate_5(cards: [Card; 5]) -> HandStrength {
311 HandStrength(score_5(cards))
312}
313
314pub(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#[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
384pub fn evaluate_7(cards: [Card; 7]) -> HandStrength {
390 HandStrength(score_7(cards))
391}
392
393fn top_rank(mask: u16) -> u32 {
395 15 - mask.leading_zeros()
396}
397
398fn 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
410fn best_straight_high(mask: u16) -> Option<u32> {
413 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 (runs != 0).then(|| top_rank(runs) + 3)
418}
419
420pub(crate) fn score_7(cards: [Card; 7]) -> u32 {
425 let mut suits = [0u16; 4];
426 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 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#[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 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 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 #[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 ); 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 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 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 #[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}