-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
190 lines (170 loc) · 5.22 KB
/
main.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
use std::{collections::HashMap, str::FromStr};
type Item = u64;
type ThrownItems = HashMap<usize, Vec<Item>>;
#[derive(Debug, Copy, Clone)]
enum OpSign {
Add,
Mul,
}
#[derive(Debug, Copy, Clone)]
enum OpVal {
Old,
Val(Item),
}
#[derive(Debug, Copy, Clone)]
struct Operation {
sign: OpSign,
val: OpVal,
}
#[derive(Debug, Clone)]
struct Monkey {
items: Vec<Item>,
operation: Operation,
divisible_by: Item,
to_monkey_true: usize,
to_monkey_false: usize,
inspections: usize,
}
struct Monkeys(Vec<Monkey>);
impl Monkeys {
fn run(&mut self, amount: usize, divide: bool) {
let common_divisor = self.0.iter().map(|m| m.divisible_by).product();
for _ in 0..amount {
for i in 0..self.0.len() {
let thrown_items = self.0[i].run_turn(common_divisor, divide);
for (id, items) in thrown_items {
self.0[id].items.extend(items);
}
}
}
}
}
impl Operation {
pub const fn resolve(&self, old: Item) -> Item {
let val = match self.val {
OpVal::Old => old,
OpVal::Val(v) => v,
};
match self.sign {
OpSign::Add => old + val,
OpSign::Mul => old * val,
}
}
}
impl Monkey {
pub fn run_turn(&mut self, common_divisor: Item, divide: bool) -> ThrownItems {
let mut items = ThrownItems::new();
self.inspections += self.items.len();
for item in self.items.drain(..) {
let mut item = self.operation.resolve(item);
if divide {
item /= 3;
}
let target = if item % self.divisible_by == 0 {
self.to_monkey_true
} else {
self.to_monkey_false
};
items.entry(target).or_default().push(item % common_divisor);
}
items
}
}
impl FromStr for Operation {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (_, op) = s
.split_once('=')
.ok_or_else(|| format!("{s} is not a valid operation"))?;
let elems: Vec<_> = op.split_whitespace().collect();
let [_, op, right]: [_; 3] = elems
.try_into()
.map_err(|_| format!("{op} should have two elements and an operator"))?;
let sign = match op {
"+" => OpSign::Add,
"*" => OpSign::Mul,
v => return Err(format!("{v} is not a valid operator")),
};
let val = match right {
"old" => OpVal::Old,
v => OpVal::Val(
v.parse()
.map_err(|_| format!("{v} is not a valid number"))?,
),
};
Ok(Self { sign, val })
}
}
impl FromStr for Monkey {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut lines = s.lines().skip(1);
let get_right = |s: Option<&str>| -> Result<String, Self::Err> {
let s = s.ok_or_else(|| String::from("Missing line"))?;
let (_, right) = s.split_once(':').ok_or_else(|| format!("{s} is invalid"))?;
Ok(right.trim().to_owned())
};
let get_last_num =
|s: &str| -> Option<usize> { s.split_whitespace().last().and_then(|v| v.parse().ok()) };
let items = get_right(lines.next())?
.split(',')
.map(str::trim)
.map(Item::from_str)
.collect::<Result<_, _>>()
.map_err(|_| "Item list is invalid".to_string())?;
let operation = get_right(lines.next()).map(|s| Operation::from_str(&s))??;
let divisible_by = lines
.next()
.and_then(get_last_num)
.ok_or_else(|| String::from("Invalid divisible by"))?
as Item;
let to_monkey_true = lines
.next()
.and_then(get_last_num)
.ok_or_else(|| String::from("Invalid TRUE target monkey"))?;
let to_monkey_false = lines
.next()
.and_then(get_last_num)
.ok_or_else(|| String::from("Invalid FALSE target monkey"))?;
Ok(Self {
items,
operation,
divisible_by,
to_monkey_false,
to_monkey_true,
inspections: 0,
})
}
}
fn main() {
let input = include_str!("../input.txt");
let monkeys: Vec<Monkey> = input
.split("\n\n")
.map(Monkey::from_str)
.collect::<Result<_, _>>()
.unwrap();
let mut monkeys_1 = Monkeys(monkeys.clone());
let mut monkeys_2 = Monkeys(monkeys);
// Part 1
monkeys_1.run(20, true);
let mut inspections: Vec<_> = monkeys_1.0.iter().map(|m| m.inspections).collect();
inspections.sort_unstable();
inspections.reverse();
println!(
"Part 1: {} * {} = {}",
inspections[0],
inspections[1],
inspections[0] * inspections[1]
);
// part 2
monkeys_2.run(10000, false);
let mut inspections: Vec<_> = monkeys_2.0.iter().map(|m| m.inspections).collect();
inspections.sort_unstable();
inspections.reverse();
println!(
"Part 2: {} * {} = {}",
inspections[0],
inspections[1],
inspections[0] * inspections[1]
);
}