use crate::card::Card;
use std::collections::HashMap;
use std::sync::OnceLock;
const CAT_HIGH_CARD: u32 = 0;
const CAT_PAIR: u32 = 1;
const CAT_TWO_PAIR: u32 = 2;
const CAT_THREE_KIND: u32 = 3;
const CAT_STRAIGHT: u32 = 4;
const CAT_FLUSH: u32 = 5;
const CAT_FULL_HOUSE: u32 = 6;
const CAT_FOUR_KIND: u32 = 7;
const CAT_STRAIGHT_FLUSH: u32 = 8;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HandCategory {
HighCard,
Pair,
TwoPair,
ThreeOfAKind,
Straight,
Flush,
FullHouse,
FourOfAKind,
StraightFlush,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HandStrength(pub(crate) u32);
impl HandStrength {
pub fn category(self) -> HandCategory {
category_of(self.0)
}
}
fn category_of(score: u32) -> HandCategory {
match score >> 20 {
CAT_HIGH_CARD => HandCategory::HighCard,
CAT_PAIR => HandCategory::Pair,
CAT_TWO_PAIR => HandCategory::TwoPair,
CAT_THREE_KIND => HandCategory::ThreeOfAKind,
CAT_STRAIGHT => HandCategory::Straight,
CAT_FLUSH => HandCategory::Flush,
CAT_FULL_HOUSE => HandCategory::FullHouse,
CAT_FOUR_KIND => HandCategory::FourOfAKind,
CAT_STRAIGHT_FLUSH => HandCategory::StraightFlush,
other => unreachable!("invalid hand category bits: {other}"),
}
}
fn pack_ranks(ranks: &[u8]) -> u32 {
let mut bits = 0u32;
for (i, &r) in ranks.iter().enumerate() {
bits |= (r as u32) << (16 - i * 4);
}
bits
}
fn pack(category: u32, ranks: &[u8]) -> u32 {
(category << 20) | pack_ranks(ranks)
}
fn straight_high(ranks_desc: &[u8]) -> Option<u8> {
if ranks_desc.len() != 5 {
return None;
}
if ranks_desc == [12, 3, 2, 1, 0] {
return Some(3);
}
for w in ranks_desc.windows(2) {
if w[0] != w[1] + 1 {
return None;
}
}
Some(ranks_desc[0])
}
#[doc(hidden)]
pub fn evaluate_5_reference(cards: [Card; 5]) -> u32 {
let mut rank_counts = [0u8; 13];
let mut suit_counts = [0u8; 4];
for &c in &cards {
rank_counts[c.rank() as usize] += 1;
suit_counts[c.suit() as usize] += 1;
}
let is_flush = suit_counts.contains(&5);
let mut ranks_desc: Vec<u8> = (0..13u8).filter(|&r| rank_counts[r as usize] > 0).collect();
ranks_desc.sort_unstable_by(|a, b| b.cmp(a));
let straight = straight_high(&ranks_desc);
if is_flush {
if let Some(high) = straight {
return pack(CAT_STRAIGHT_FLUSH, &[high]);
}
}
let mut groups: Vec<(u8, u8)> = (0..13u8)
.filter(|&r| rank_counts[r as usize] > 0)
.map(|r| (rank_counts[r as usize], r))
.collect();
groups.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));
match groups[0].0 {
4 => pack(CAT_FOUR_KIND, &[groups[0].1, groups[1].1]),
3 if groups[1].0 >= 2 => pack(CAT_FULL_HOUSE, &[groups[0].1, groups[1].1]),
3 => pack(CAT_THREE_KIND, &[groups[0].1, groups[1].1, groups[2].1]),
2 if groups[1].0 == 2 => pack(CAT_TWO_PAIR, &[groups[0].1, groups[1].1, groups[2].1]),
2 => pack(
CAT_PAIR,
&[groups[0].1, groups[1].1, groups[2].1, groups[3].1],
),
_ if is_flush => {
let ranks: Vec<u8> = groups.iter().map(|g| g.1).collect();
pack(CAT_FLUSH, &ranks)
}
_ if straight.is_some() => pack(CAT_STRAIGHT, &[straight.unwrap()]),
_ => {
let ranks: Vec<u8> = groups.iter().map(|g| g.1).collect();
pack(CAT_HIGH_CARD, &ranks)
}
}
}
const RANK_PRIMES: [u64; 13] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];
struct Tables {
straight_high: Vec<Option<u8>>,
high_card_tiebreak: Vec<u32>,
paired: HashMap<u64, u32>,
}
static TABLES: OnceLock<Tables> = OnceLock::new();
fn tables() -> &'static Tables {
TABLES.get_or_init(build_tables)
}
fn build_tables() -> Tables {
let mut straight_high_table = vec![None; 8192];
let mut high_card_tiebreak = vec![0u32; 8192];
for mask in 0u16..8192 {
if mask.count_ones() != 5 {
continue;
}
let ranks_desc: Vec<u8> = (0..13u8).rev().filter(|&r| mask & (1 << r) != 0).collect();
straight_high_table[mask as usize] = straight_high(&ranks_desc);
high_card_tiebreak[mask as usize] = pack_ranks(&ranks_desc);
}
let mut paired = HashMap::new();
for ranks in rank_multisets_with_repeat() {
let hand = representative_hand(&ranks);
let score = evaluate_5_reference(hand);
let product: u64 = ranks.iter().map(|&r| RANK_PRIMES[r as usize]).product();
paired.insert(product, score);
}
Tables {
straight_high: straight_high_table,
high_card_tiebreak,
paired,
}
}
fn rank_multisets_with_repeat() -> Vec<[u8; 5]> {
let mut out = Vec::new();
for r0 in 0..13u8 {
for r1 in 0..=r0 {
for r2 in 0..=r1 {
for r3 in 0..=r2 {
for r4 in 0..=r3 {
let ranks = [r0, r1, r2, r3, r4];
let mut counts = [0u8; 13];
for &r in &ranks {
counts[r as usize] += 1;
}
let max_count = counts.iter().copied().max().unwrap();
if (2..=4).contains(&max_count) {
out.push(ranks);
}
}
}
}
}
}
out
}
fn representative_hand(ranks: &[u8; 5]) -> [Card; 5] {
let mut next_suit = [0u8; 13];
let mut cards = [Card(0); 5];
for (i, &r) in ranks.iter().enumerate() {
let s = next_suit[r as usize];
next_suit[r as usize] += 1;
cards[i] = Card(r * 4 + s);
}
cards
}
pub fn evaluate_5(cards: [Card; 5]) -> HandStrength {
HandStrength(score_5(cards))
}
pub(crate) fn score_5(cards: [Card; 5]) -> u32 {
debug_assert!(
crate::card::CardSet::from_cards(&cards).len() == 5,
"evaluate_5 needs five distinct cards"
);
let t = tables();
let mut suit_counts = [0u8; 4];
let mut rank_mask: u16 = 0;
let mut has_repeat = false;
for &c in &cards {
let r = c.rank();
suit_counts[c.suit() as usize] += 1;
let bit = 1u16 << r;
if rank_mask & bit != 0 {
has_repeat = true;
}
rank_mask |= bit;
}
let is_flush = suit_counts.contains(&5);
if !has_repeat {
if let Some(high) = t.straight_high[rank_mask as usize] {
let cat = if is_flush {
CAT_STRAIGHT_FLUSH
} else {
CAT_STRAIGHT
};
return pack(cat, &[high]);
}
let cat = if is_flush { CAT_FLUSH } else { CAT_HIGH_CARD };
return (cat << 20) | t.high_card_tiebreak[rank_mask as usize];
}
let product: u64 = cards
.iter()
.map(|&c| RANK_PRIMES[c.rank() as usize])
.product();
*t.paired
.get(&product)
.expect("every 5-card rank multiset is precomputed in `paired`")
}
const COMBOS_7_CHOOSE_5: [[usize; 5]; 21] = [
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 5],
[0, 1, 2, 3, 6],
[0, 1, 2, 4, 5],
[0, 1, 2, 4, 6],
[0, 1, 2, 5, 6],
[0, 1, 3, 4, 5],
[0, 1, 3, 4, 6],
[0, 1, 3, 5, 6],
[0, 1, 4, 5, 6],
[0, 2, 3, 4, 5],
[0, 2, 3, 4, 6],
[0, 2, 3, 5, 6],
[0, 2, 4, 5, 6],
[0, 3, 4, 5, 6],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 6],
[1, 2, 3, 5, 6],
[1, 2, 4, 5, 6],
[1, 3, 4, 5, 6],
[2, 3, 4, 5, 6],
];
pub fn evaluate_7(cards: [Card; 7]) -> HandStrength {
HandStrength(score_7(cards))
}
pub(crate) fn score_7(cards: [Card; 7]) -> u32 {
COMBOS_7_CHOOSE_5
.iter()
.map(|combo| {
let five = [
cards[combo[0]],
cards[combo[1]],
cards[combo[2]],
cards[combo[3]],
cards[combo[4]],
];
score_5(five)
})
.max()
.expect("21 combos is never empty")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::card::Card;
fn hand5(cards: &str) -> [Card; 5] {
let parsed: Vec<Card> = cards
.split_whitespace()
.map(|c| c.parse::<Card>().unwrap())
.collect();
parsed.try_into().unwrap()
}
fn hand7(cards: &str) -> [Card; 7] {
let parsed: Vec<Card> = cards
.split_whitespace()
.map(|c| c.parse::<Card>().unwrap())
.collect();
parsed.try_into().unwrap()
}
#[test]
fn categorizes_each_hand_type() {
assert_eq!(
evaluate_5(hand5("As Ks Qs Js Ts")).category(),
HandCategory::StraightFlush
);
assert_eq!(
evaluate_5(hand5("5s 4s 3s 2s As")).category(),
HandCategory::StraightFlush
); assert_eq!(
evaluate_5(hand5("Ah Ad As Ac Kh")).category(),
HandCategory::FourOfAKind
);
assert_eq!(
evaluate_5(hand5("Ah Ad As Kh Kd")).category(),
HandCategory::FullHouse
);
assert_eq!(
evaluate_5(hand5("Ah 9h 7h 4h 2h")).category(),
HandCategory::Flush
);
assert_eq!(
evaluate_5(hand5("9h 8d 7s 6h 5c")).category(),
HandCategory::Straight
);
assert_eq!(
evaluate_5(hand5("Ah Ad As Kh Qd")).category(),
HandCategory::ThreeOfAKind
);
assert_eq!(
evaluate_5(hand5("Ah Ad Kh Kd Qc")).category(),
HandCategory::TwoPair
);
assert_eq!(
evaluate_5(hand5("Ah Ad Kh Qd Jc")).category(),
HandCategory::Pair
);
assert_eq!(
evaluate_5(hand5("Ah Kd Qh Jd 9c")).category(),
HandCategory::HighCard
);
}
#[test]
fn wheel_straight_loses_to_six_high_straight() {
let wheel = evaluate_5(hand5("5s 4s 3d 2c As"));
let six_high = evaluate_5(hand5("6s 5d 4d 3c 2h"));
assert!(six_high > wheel);
}
#[test]
fn higher_trips_beats_lower_trips_in_full_house() {
let aces_full = evaluate_5(hand5("Ah Ad As Kh Kd"));
let kings_full = evaluate_5(hand5("Kh Kd Ks Ah Ad"));
assert!(aces_full > kings_full);
}
#[test]
fn flush_beats_straight_beats_trips() {
let flush = evaluate_5(hand5("Ah 9h 7h 4h 2h"));
let straight = evaluate_5(hand5("9h 8d 7s 6h 5c"));
let trips = evaluate_5(hand5("Ah Ad As Kh Qd"));
assert!(flush > straight);
assert!(straight > trips);
}
#[test]
fn evaluate_7_picks_best_two_pair_from_three_pairs() {
let best = evaluate_7(hand7("2c 3d Ah Ad Kh Kd Qh"));
let expected = evaluate_5(hand5("Ah Ad Kh Kd Qh"));
assert_eq!(best, expected);
assert_eq!(best.category(), HandCategory::TwoPair);
}
#[test]
fn evaluate_7_finds_straight_using_board_and_hole_cards() {
let best = evaluate_7(hand7("9h 8d 7s 6h 5c 2d 2s"));
assert_eq!(best.category(), HandCategory::Straight);
let expected = evaluate_5(hand5("9h 8d 7s 6h 5c"));
assert_eq!(best, expected);
}
#[test]
fn evaluate_5_matches_reference_for_every_possible_hand() {
let mut checked = 0u64;
for a in 0u8..52 {
for b in (a + 1)..52 {
for c in (b + 1)..52 {
for d in (c + 1)..52 {
for e in (d + 1)..52 {
let hand = [a, b, c, d, e].map(Card);
let fast = score_5(hand);
let reference = evaluate_5_reference(hand);
assert_eq!(fast, reference, "mismatch for hand {hand:?}");
checked += 1;
}
}
}
}
}
assert_eq!(checked, 2_598_960);
}
}