-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_11.rs
214 lines (182 loc) · 5.4 KB
/
day_11.rs
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use primes::{PrimeSet, Sieve};
use std::vec;
use itertools::Itertools;
fn lowest_common_multiple(nums: Vec<u64>) -> u64 {
let mut pset = Sieve::new();
let mut table = nums.into_iter();
let mut prime_iter = pset.iter();
let mut divisors: Vec<u64> = vec![];
let mut prime = prime_iter.next().unwrap();
while !table.clone().all(|n| n == 1) {
if table.clone().any(|n| n % prime == 0) {
divisors.push(prime);
table = table
.map(|n| match n % prime == 0 {
true => n / prime,
false => n,
})
.collect_vec()
.into_iter();
} else {
prime = prime_iter.next().unwrap();
}
}
divisors.iter().product::<u64>()
}
#[derive(Debug, Clone, Copy)]
enum Operator {
Add,
Multiply,
}
#[derive(Debug, Clone)]
struct Operation {
val: String,
operator: Operator,
}
impl Operation {
fn from(raw_operation: &str) -> Operation {
let mut parts = raw_operation.split(' ');
parts.next();
Operation {
operator: match parts.next().unwrap() {
"+" => Operator::Add,
"*" => Operator::Multiply,
_ => panic!("Unknown operator"),
},
val: parts.next().unwrap().to_string(),
}
}
fn apply(&self, item: u64) -> u64 {
match self.operator {
Operator::Add => item + self.val.parse().unwrap_or(item),
Operator::Multiply => item * self.val.parse().unwrap_or(item),
}
}
}
#[derive(Debug, Clone, Copy)]
struct Test {
divisor: u64,
true_monkey: usize,
false_monkey: usize,
}
impl Test {
fn from(raw_test: Vec<&str>) -> Test {
let mut nums = raw_test
.iter()
.map(|s| s.split(' ').last().unwrap().parse::<u64>().unwrap());
Test {
divisor: nums.next().unwrap(),
true_monkey: nums.next().unwrap() as usize,
false_monkey: nums.next().unwrap() as usize,
}
}
fn run(self, worry_level: u64) -> usize {
if worry_level % self.divisor == 0 {
self.true_monkey
} else {
self.false_monkey
}
}
}
#[derive(Debug, Clone)]
struct Monkey {
inspect_count: u64,
items: Vec<u64>,
operation: Operation,
test: Test,
}
impl Monkey {
fn from(raw_monkey: &str) -> Monkey {
let mut lines = raw_monkey.lines();
lines.next();
let items = lines
.next()
.unwrap()
.split(':')
.nth(1)
.unwrap()
.trim()
.split(", ")
.map(|s| s.parse::<u64>().unwrap())
.collect_vec();
let operation = lines.next().unwrap().split('=').nth(1).unwrap().trim();
let test = lines.collect_vec();
Monkey {
inspect_count: 0,
items,
operation: Operation::from(operation),
test: Test::from(test),
}
}
fn inspect(&mut self, idx: usize, reduce_stress: &dyn Fn(u64) -> u64) -> (usize, u64) {
let item = self.items[idx];
let mut worry_level = self.operation.apply(item);
worry_level = reduce_stress(worry_level);
let target_monkey = self.test.run(worry_level);
(target_monkey, worry_level)
}
}
pub fn part_1(input: &str) -> u64 {
let monkeys = input.split("\n\n").map(Monkey::from).collect_vec();
let rounds = 20;
let reduce_stress = |worry_level: u64| worry_level / 3;
monkey_business(monkeys, rounds, &reduce_stress)
}
pub fn part_2(input: &str) -> u64 {
let monkeys = input.split("\n\n").map(Monkey::from).collect_vec();
let rounds = 10_000;
let lcm = lowest_common_multiple(monkeys.iter().map(|m| m.test.divisor).collect_vec());
let reduce_stress = |worry_level: u64| worry_level % lcm;
monkey_business(monkeys, rounds, &reduce_stress)
}
fn monkey_business(
mut monkeys: Vec<Monkey>,
rounds: u64,
reduce_stress: &dyn Fn(u64) -> u64,
) -> u64 {
for _ in 0..rounds {
for monkey_idx in 0..monkeys.len() {
let mut monkey = monkeys[monkey_idx].clone();
for item_idx in 0..monkey.items.len() {
let (target_monkey, item) = monkey.inspect(item_idx, &reduce_stress);
monkeys[monkey_idx].inspect_count += 1;
monkeys[monkey_idx].items.remove(0);
monkeys[target_monkey].items.push(item);
}
}
}
monkeys.sort_by(|a, b| b.inspect_count.cmp(&a.inspect_count));
monkeys
.iter()
.take(2)
.fold(1, |acc, m| acc * m.inspect_count)
}
#[cfg(test)]
mod tests {
use crate::get_input;
use super::*;
#[test]
fn test_part_1_dummy() {
let input = get_input("2022", "11", Some("dummy"));
let output = part_1(&input);
assert_eq!(output, 10605);
}
#[test]
fn test_part_1() {
let input = get_input("2022", "11", None);
let output = part_1(&input);
assert_eq!(output, 56595);
}
#[test]
fn test_part_2_dummy() {
let input = get_input("2022", "11", Some("dummy"));
let output = part_2(&input);
assert_eq!(output, 2713310158);
}
#[test]
fn test_part_2() {
let input = get_input("2022", "11", None);
let output = part_2(&input);
assert_eq!(output, 15693274740);
}
}