Files
pokerfreak/src/hand/five.rs
T

79 lines
2.8 KiB
Rust

//! Exact evaluation of five cards.
use super::category::Category;
use super::strength::Strength;
use crate::card::Card;
use crate::variant::{DeckRule, HandRanking};
/// Standard rules, full deck (ace low in A-2-3-4-5 only).
pub fn evaluate(cards: &[Card; 5]) -> Strength {
evaluate_in(DeckRule::FULL, HandRanking::Standard, cards)
}
/// Five cards under a deck rule (where the ace plays low) and a category ranking.
pub fn evaluate_in(deck: DeckRule, ranking: HandRanking, cards: &[Card; 5]) -> Strength {
let counts = rank_counts(cards);
let groups = groups_by_weight(&counts);
let flush = cards.iter().all(|c| c.suit == cards[0].suit);
let straight_high = straight_high(deck, &groups);
let ranks = tie_break(&groups);
let category = match (straight_high, flush, groups[0].0, groups[1].0) {
(Some(_), true, _, _) => Category::StraightFlush,
(_, _, 4, _) => Category::FourOfAKind,
(_, _, 3, 2) => Category::FullHouse,
(_, true, _, _) => Category::Flush,
(Some(_), _, _, _) => Category::Straight,
(_, _, 3, _) => Category::ThreeOfAKind,
(_, _, 2, 2) => Category::TwoPair,
(_, _, 2, _) => Category::Pair,
_ => Category::HighCard,
};
let ranks = match (category, straight_high) {
(Category::Straight | Category::StraightFlush, Some(high)) => [high, 0, 0, 0, 0],
_ => ranks,
};
Strength::new(ranking, category, ranks)
}
fn rank_counts(cards: &[Card; 5]) -> [u8; 15] {
let mut counts = [0u8; 15];
cards.iter().for_each(|c| counts[c.rank.value() as usize] += 1);
counts
}
/// `(count, rank)` pairs, most numerous first, then highest rank; unused slots `(0, 0)`.
fn groups_by_weight(counts: &[u8; 15]) -> [(u8, u8); 5] {
let mut groups = [(0u8, 0u8); 5];
let mut filled = 0;
for rank in (2..=14u8).rev() {
let count = counts[rank as usize];
if count > 0 {
groups[filled] = (count, rank);
filled += 1;
}
}
groups.sort_by(|a, b| b.cmp(a));
groups
}
fn tie_break(groups: &[(u8, u8); 5]) -> [u8; 5] {
let mut ranks = [0u8; 5];
groups.iter().enumerate().for_each(|(i, g)| ranks[i] = g.1);
ranks
}
/// High card of the straight when the five cards are five consecutive ranks.
/// The ace also plays below the deck's lowest rank: A-2-3-4-5 (five high) in the full deck,
/// A-6-7-8-9 (nine high) in the short deck.
fn straight_high(deck: DeckRule, groups: &[(u8, u8); 5]) -> Option<u8> {
let distinct = groups.iter().all(|g| g.0 == 1);
let ranks = tie_break(groups); // descending because all counts are 1
let low = deck.lowest.value();
match (distinct, ranks) {
(false, _) => None,
(true, [14, a, b, c, d]) if [a, b, c, d] == [low + 3, low + 2, low + 1, low] => Some(low + 3),
(true, r) if r[0] - r[4] == 4 => Some(r[0]),
_ => None,
}
}