1use std::array::from_fn;
47use std::ops::{Add, Mul, Sub};
48
49use crate::util::hash::*;
50use crate::util::iter::*;
51use crate::util::parse::*;
52use crate::util::thread::*;
53
54type Input = (Vec<Monkey>, Vec<Pair>);
55type Pair = (usize, u64);
56
57pub struct Monkey {
58 items: Vec<u64>,
59 operation: Operation,
60 test: u64,
61 yes: usize,
62 no: usize,
63}
64
65impl Monkey {
66 fn inspect(&self, item: u64) -> u64 {
68 match self.operation {
69 Operation::Square => item * item,
70 Operation::Multiply(y) => item * y,
71 Operation::Add(y) => item + y,
72 }
73 }
74
75 fn throw(&self, item: u64) -> usize {
77 if item.is_multiple_of(self.test) { self.yes } else { self.no }
78 }
79}
80
81enum Operation {
82 Square,
83 Multiply(u64),
84 Add(u64),
85}
86
87#[derive(Clone, Copy, Default)]
88struct Business([usize; 8]);
89
90impl Business {
91 fn inc(&mut self, from: usize) {
92 self.0[from] += 1;
93 }
94
95 fn level(mut self) -> usize {
96 self.0.sort_unstable();
97 self.0.iter().rev().take(2).product()
98 }
99}
100
101impl Add for Business {
103 type Output = Self;
104
105 #[inline]
106 fn add(self, rhs: Self) -> Self {
107 Self(from_fn(|i| self.0[i] + rhs.0[i]))
108 }
109}
110
111impl Sub for Business {
112 type Output = Self;
113
114 #[inline]
115 fn sub(self, rhs: Self) -> Self {
116 Self(from_fn(|i| self.0[i] - rhs.0[i]))
117 }
118}
119
120impl Mul<usize> for Business {
121 type Output = Self;
122
123 #[inline]
124 fn mul(self, rhs: usize) -> Self {
125 Self(self.0.map(|n| n * rhs))
126 }
127}
128
129pub fn parse(input: &str) -> Input {
132 let lines: Vec<_> = input.lines().collect();
133
134 let monkeys: Vec<_> = lines
135 .chunks(7)
136 .map(|chunk| {
137 let items = chunk[1].iter_unsigned().collect();
138 let operation = match chunk[2].rsplit(' ').chunk::<2>().next().unwrap() {
139 ["old", _] => Operation::Square,
140 [y, "*"] => Operation::Multiply(y.unsigned()),
141 [y, "+"] => Operation::Add(y.unsigned()),
142 _ => unreachable!(),
143 };
144 let test = chunk[3].unsigned();
145 let yes = chunk[4].unsigned();
146 let no = chunk[5].unsigned();
147 Monkey { items, operation, test, yes, no }
148 })
149 .collect();
150
151 let pairs = monkeys
152 .iter()
153 .enumerate()
154 .flat_map(|(from, monkey)| monkey.items.iter().map(move |&item| (from, item)))
155 .collect();
156
157 (monkeys, pairs)
158}
159
160pub fn part1(input: &Input) -> usize {
161 let (monkeys, pairs) = input;
162 let mut business = Business::default();
163
164 for &(mut from, mut item) in pairs {
165 let mut rounds = 0;
166
167 while rounds < 20 {
168 item = monkeys[from].inspect(item) / 3;
169 let to = monkeys[from].throw(item);
170
171 business.inc(from);
172
173 rounds += usize::from(to < from);
176 from = to;
177 }
178 }
179
180 business.level()
181}
182
183pub fn part2(input: &Input) -> usize {
184 let (monkeys, pairs) = input;
185
186 let result = spawn_parallel_iterator(pairs, |iter| {
188 iter.map(|&(from, item)| play(monkeys, from, item)).collect::<Vec<_>>()
189 });
190
191 result.into_iter().flatten().fold(Business::default(), Business::add).level()
193}
194
195fn play(monkeys: &[Monkey], mut from: usize, mut item: u64) -> Business {
198 let product: u64 = monkeys.iter().map(|m| m.test).product();
199
200 let mut round = 0;
201 let mut business = Business::default();
202
203 let mut path = vec![business];
204 let mut seen = FastMap::build([((from, item), round)]);
205
206 while round < 10_000 {
207 item = monkeys[from].inspect(item) % product;
208 let to = monkeys[from].throw(item);
209
210 business.inc(from);
211
212 if to < from {
215 round += 1;
216 path.push(business);
217
218 if let Some(previous) = seen.insert((to, item), round) {
220 let cycle_width = round - previous;
221
222 let offset = 10_000 - round;
223 let quotient = offset / cycle_width;
224 let remainder = offset % cycle_width;
225
226 let full = (business - path[previous]) * quotient;
227 let partial = path[previous + remainder] - path[previous];
228 return business + full + partial;
229 }
230 }
231
232 from = to;
233 }
234
235 business
236}