summaryrefslogtreecommitdiffstats
path: root/src/day_07.rs
blob: 5beebbe683262e6151e67f91772341660df0b36b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use std::{cmp::Reverse, collections::BTreeMap, str::FromStr};

use anyhow::Context;

use crate::{Problem, Solution};

pub struct Day07;

impl Problem for Day07 {
    const DAY: u8 = 7;

    const INPUT: &'static str = include_str!("../input/day_07.txt");
}

impl Solution for Day07 {
    type Answer1 = usize;

    type Answer2 = usize;

    fn part_1(input: &str) -> anyhow::Result<Self::Answer1> {
        let hand_bets = input
            .lines()
            .map(|s| {
                s.trim()
                    .split_once(' ')
                    .with_context(|| format!("Invalid had format: {s}"))
                    .and_then(|(hand, bet)| anyhow::Ok((Reverse(hand.parse()?), bet.parse()?)))
            })
            .try_collect::<BTreeMap<Reverse<Hand<false>>, usize>>()?;

        Ok(hand_bets
            .into_values()
            .enumerate()
            .map(|(i, bid)| bid * (i + 1))
            .sum())
    }

    fn part_2(input: &str) -> anyhow::Result<Self::Answer2> {
        let hand_bets = input
            .lines()
            .map(|s| {
                s.trim()
                    .split_once(' ')
                    .with_context(|| format!("Invalid had format: {s}"))
                    .and_then(|(hand, bet)| anyhow::Ok((Reverse(hand.parse()?), bet.parse()?)))
            })
            .try_collect::<BTreeMap<Reverse<Hand<true>>, usize>>()?;

        Ok(hand_bets
            .into_values()
            .enumerate()
            .map(|(i, bid)| bid * (i + 1))
            .sum())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Hand<const WILD: bool> {
    FiveOfAKind([Card<WILD>; 5]),
    FourOfAKind([Card<WILD>; 5]),
    FullHouse([Card<WILD>; 5]),
    ThreeOfAKind([Card<WILD>; 5]),
    TwoPair([Card<WILD>; 5]),
    OnePair([Card<WILD>; 5]),
    HighCard([Card<WILD>; 5]),
}

impl<const WILD: bool> Hand<WILD> {
    fn count_types(mut cards: [Card<WILD>; 5]) -> (Vec<usize>, usize) {
        cards.sort();

        cards
            .array_windows()
            .rev()
            .fold((Vec::from([1]), 0), |(mut acc, mut wilds), arr| {
                match arr {
                    [Card::Joker, Card::Joker] if wilds == 0 => wilds += 1,
                    [_, Card::Joker] => wilds += 1,
                    [p, n] if p == n => *acc.last_mut().unwrap() += 1,
                    _ => acc.push(1),
                }

                (acc, wilds)
            })
    }
}

impl<const WILD: bool> From<[Card<WILD>; 5]> for Hand<WILD> {
    fn from(cards: [Card<WILD>; 5]) -> Self {
        let (mut counts, wilds) = Hand::count_types(cards);
        counts.sort();

        let n = counts.pop().unwrap();
        let has_2 = counts.pop().is_some_and(|m| m == 2);

        match (n + wilds).min(5) {
            5 => Self::FiveOfAKind(cards),
            4 => Self::FourOfAKind(cards),
            3 if has_2 => Self::FullHouse(cards),
            3 => Self::ThreeOfAKind(cards),
            2 if has_2 => Self::TwoPair(cards),
            2 => Self::OnePair(cards),
            _ => Self::HighCard(cards),
        }
    }
}
impl<const WILD: bool> FromStr for Hand<WILD> {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let cards: [Card<WILD>; 5] = s
            .chars()
            .map(Card::try_from)
            .try_collect::<Vec<_>>()?
            .try_into()
            .map_err(|v| anyhow::format_err!("Incorrect number of cards: {v:?}"))?;

        Ok(Self::from(cards))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Card<const WILD: bool> {
    Ace,
    King,
    Queen,
    Jack,
    Ten,
    Nine,
    Eight,
    Seven,
    Six,
    Five,
    Four,
    Three,
    Two,
    Joker,
}

impl<const WILD: bool> TryFrom<char> for Card<WILD> {
    type Error = anyhow::Error;

    fn try_from(value: char) -> Result<Self, Self::Error> {
        Ok(match value {
            'A' => Card::Ace,
            'K' => Card::King,
            'Q' => Card::Queen,
            'J' if WILD => Card::Joker,
            'J' => Card::Jack,
            'T' => Card::Ten,
            '9' => Card::Nine,
            '8' => Card::Eight,
            '7' => Card::Seven,
            '6' => Card::Six,
            '5' => Card::Five,
            '4' => Card::Four,
            '3' => Card::Three,
            '2' => Card::Two,
            c => anyhow::bail!("Failed to parse card value: {c}"),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const INPUT: &str = indoc::indoc! {"
        32T3K 765
        T55J5 684
        KK677 28
        KTJJT 220
        QQQJA 483
    "};

    #[test]
    fn test_part_1() -> anyhow::Result<()> {
        Ok(assert_eq!(6440, Day07::part_1(INPUT)?))
    }

    #[test]
    fn test_part_2() -> anyhow::Result<()> {
        Ok(assert_eq!(5905, Day07::part_2(INPUT)?))
    }
}