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
358const 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
383pub fn evaluate_7(cards: [Card; 7]) -> HandStrength {
389 HandStrength(score_7(cards))
390}
391
392pub(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 ); 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 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 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 #[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}