summaryrefslogtreecommitdiffstats
path: root/src/bin/2022/day11.rs
blob: faef1953d054a47bf3b561ab8169c5a7dfc30214 (plain) (blame)
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
#![allow(dead_code)]
#![allow(unused_variables)]

use advent_of_code::prelude::*;

pub struct Monkey {
    items: VecDeque<u64>,
    op: Box<dyn Fn(u64) -> u64>,
    divisor: u64,
    modulo: u64,
    test: u64,
    if_true: usize,
    if_false: usize,

    count: u64,
}

impl std::fmt::Debug for Monkey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Monkey")
            .field("items", &self.items)
            .finish()
    }
}

impl Monkey {
    fn parse(mut it: impl Iterator<Item = String>) -> Monkey {
        let line = it.next().unwrap();
        let cap = regex_captures!(r"^  Starting items: ([0-9, ]*)$", &line)
            .unwrap();
        let items = cap[1].split(", ").map(|s| s.parse().unwrap()).collect();

        let line = it.next().unwrap();
        let cap = regex_captures!(
            r"^  Operation: new = old ([+*]) (\d+|old)$",
            &line
        )
        .unwrap();
        let op = if &cap[2] == "old" {
            match &cap[1] {
                "+" => Box::new(move |x| x + x) as Box<dyn Fn(u64) -> u64>,
                "*" => Box::new(move |x| x * x),
                _ => unreachable!(),
            }
        } else {
            let n: u64 = cap[2].parse().unwrap();
            match &cap[1] {
                "+" => Box::new(move |x| x + n) as Box<dyn Fn(u64) -> u64>,
                "*" => Box::new(move |x| x * n),
                _ => unreachable!(),
            }
        };

        let line = it.next().unwrap();
        let cap =
            regex_captures!(r"^  Test: divisible by (\d+)$", &line).unwrap();
        let test = cap[1].parse().unwrap();

        let line = it.next().unwrap();
        let cap =
            regex_captures!(r"^    If true: throw to monkey (\d+)$", &line)
                .unwrap();
        let if_true = cap[1].parse().unwrap();

        let line = it.next().unwrap();
        let cap =
            regex_captures!(r"^    If false: throw to monkey (\d+)$", &line)
                .unwrap();
        let if_false = cap[1].parse().unwrap();

        assert!(it.next().is_none());

        Self {
            items,
            op,
            divisor: 0,
            modulo: 0,
            test,
            if_true,
            if_false,
            count: 0,
        }
    }

    fn inspect(&mut self) -> Option<(u64, usize)> {
        let Some(item) = self.items.pop_front()
        else { return None };
        self.count += 1;
        let item = (self.op)(item);
        let item = item / self.divisor;
        let item = item % self.modulo;
        if item % self.test == 0 {
            Some((item, self.if_true))
        } else {
            Some((item, self.if_false))
        }
    }

    fn catch(&mut self, item: u64) {
        self.items.push_back(item);
    }

    fn set_reduce(&mut self, divisor: u64, modulo: u64) {
        self.divisor = divisor;
        self.modulo = modulo;
    }
}

#[derive(Debug)]
pub struct Monkeys {
    monkeys: Vec<Monkey>,
}

impl Monkeys {
    fn parse(it: impl Iterator<Item = String>) -> Self {
        let mut monkeys = vec![];
        let mut it = it.peekable();
        while it.peek().is_some() {
            let header = it.next().unwrap();
            let cap = regex_captures!(r"^Monkey (\d+):$", &header).unwrap();
            let monkey_idx: usize = cap[1].parse().unwrap();
            assert_eq!(monkey_idx, monkeys.len());
            monkeys.push(Monkey::parse(parse::chunk(&mut it)));
        }
        Self { monkeys }
    }

    fn round(&mut self) {
        for i in 0..self.monkeys.len() {
            while let Some((item, to)) = self.monkeys[i].inspect() {
                self.monkeys[to].catch(item);
            }
        }
    }

    fn monkey_business(&self) -> u64 {
        let mut counts: Vec<_> =
            self.monkeys.iter().map(|m| m.count).collect();
        counts.sort_unstable();
        counts[counts.len() - 1] * counts[counts.len() - 2]
    }

    fn set_reduce(&mut self, divisor: u64) {
        let modulo = self.monkeys.iter().map(|m| m.test).product();
        for monkey in &mut self.monkeys {
            monkey.set_reduce(divisor, modulo);
        }
    }
}

pub fn parse(fh: File) -> Result<Monkeys> {
    Ok(Monkeys::parse(parse::raw_lines(fh)))
}

pub fn part1(mut monkeys: Monkeys) -> Result<u64> {
    monkeys.set_reduce(3);
    for i in 0..20 {
        monkeys.round();
    }
    Ok(monkeys.monkey_business())
}

pub fn part2(mut monkeys: Monkeys) -> Result<u64> {
    monkeys.set_reduce(1);
    for i in 0..10_000 {
        monkeys.round();
    }
    Ok(monkeys.monkey_business())
}

#[test]
fn test() {
    assert_eq!(
        part1(parse(parse::data(2022, 11).unwrap()).unwrap()).unwrap(),
        51075
    );
    assert_eq!(
        part2(parse(parse::data(2022, 11).unwrap()).unwrap()).unwrap(),
        11741456163
    );
}