day 7 part 2

This commit is contained in:
Andy Teijelo 2023-12-07 18:38:45 -05:00
parent 6b09514019
commit adda315684

View file

@ -16,6 +16,20 @@ enum HandType {
} }
fn hand_type(hand: &str) -> HandType { fn hand_type(hand: &str) -> HandType {
let counter_without_joker: Counter<char> = hand.chars().filter(|c| *c != 'J').collect();
if counter_without_joker.is_empty() {
// it's JJJJJ
return HandType::FiveOfAKind;
}
let hand = hand.replace(
'J',
&counter_without_joker
.k_most_common_ordered(1)
.first()
.unwrap()
.0
.to_string(),
);
let counter: Counter<char> = hand.chars().collect(); let counter: Counter<char> = hand.chars().collect();
if counter.keys().len() == 1 { if counter.keys().len() == 1 {
return HandType::FiveOfAKind; return HandType::FiveOfAKind;
@ -54,7 +68,7 @@ fn hand_cmp_key(hand: &str) -> CmpKey {
(HandType::OnePair, 2u8), (HandType::OnePair, 2u8),
(HandType::HighCard, 1u8), (HandType::HighCard, 1u8),
]); ]);
let card_strength: HashMap<char, u8> = "AKQJT98765432" let card_strength: HashMap<char, u8> = "AKQT98765432J"
.chars() .chars()
.enumerate() .enumerate()
.map(|(i, c)| (c, (14 - i) as u8)) .map(|(i, c)| (c, (14 - i) as u8))
@ -92,12 +106,14 @@ mod tests {
#[test] #[test]
fn test_hand_types() { fn test_hand_types() {
assert_eq!(hand_type("AAAAA"), HandType::FiveOfAKind); assert_eq!(hand_type("AAAAJ"), HandType::FiveOfAKind);
assert_eq!(hand_type("AA8AA"), HandType::FourOfAKind); assert_eq!(hand_type("AAAJJ"), HandType::FiveOfAKind);
assert_eq!(hand_type("23332"), HandType::FullHouse); assert_eq!(hand_type("AAJJJ"), HandType::FiveOfAKind);
assert_eq!(hand_type("TTT98"), HandType::ThreeOfAKind); assert_eq!(hand_type("T55J5"), HandType::FourOfAKind);
assert_eq!(hand_type("23432"), HandType::TwoPair); assert_eq!(hand_type("KTJJT"), HandType::FourOfAKind);
assert_eq!(hand_type("A23A4"), HandType::OnePair); assert_eq!(hand_type("QQQJA"), HandType::FourOfAKind);
assert_eq!(hand_type("2J432"), HandType::ThreeOfAKind);
assert_eq!(hand_type("A23J4"), HandType::OnePair);
assert_eq!(hand_type("23456"), HandType::HighCard); assert_eq!(hand_type("23456"), HandType::HighCard);
} }
} }