-
Notifications
You must be signed in to change notification settings - Fork 0
/
day16.rs
273 lines (228 loc) · 7.73 KB
/
day16.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! [Day 16: Proboscidea Volcanium](https://adventofcode.com/2022/day/16)
use regex::Regex;
use std::collections::HashMap;
struct Puzzle {
valves: HashMap<String, u8>,
flow_rates: HashMap<u8, u32>,
tunnels: HashMap<u8, Vec<u8>>,
distances: [[u32; 128]; 128],
}
impl Puzzle {
fn new() -> Self {
Self {
valves: HashMap::new(),
flow_rates: HashMap::new(),
tunnels: HashMap::new(),
distances: [[0u32; 128]; 128],
}
}
/// Loads data from input (one line)
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
let re = Regex::new(
r"Valve (\w\w) has flow rate=(\d+); tunnels? leads? to valves? ((?:\w\w)(?:, \w\w)*)$",
)
.unwrap();
for line in data.split('\n').collect::<Vec<_>>() {
if let Some(m) = re.captures(line) {
let valve = self.valve_id_new(&m[1]);
let rate = m[2].parse::<u32>().unwrap();
if rate != 0 {
self.flow_rates.insert(valve, rate);
}
let dest = m[3].split(", ").map(|x| self.valve_id_new(x)).collect();
self.tunnels.insert(valve, dest);
}
}
// since we use a u128 bitfield for list of valves, there can be no more than 64
// and valve ID are between 0 and127 included
assert!(self.valves.len() <= 128);
// precompute distance between valves
let max_id = self.valves.len();
for a in 0..max_id {
for b in 0..max_id {
let d = self.calc_dist(a as u8, b as u8, 0);
self.distances[a][b] = d;
}
}
}
fn distance(&self, a: u8, b: u8) -> u32 {
self.distances[a as usize][b as usize]
}
fn calc_dist(&self, a: u8, b: u8, visited: u128) -> u32 {
let d = self.distance(a, b);
if d != 0 {
d
} else if a == b {
0
} else if (1u128 << b) & visited != 0 {
u32::MAX - 1
} else {
let b_visited = visited + (1u128 << b);
self.tunnels[&b]
.iter()
.map(|x| self.calc_dist(a, *x, b_visited))
.min()
.unwrap()
+ 1
}
}
/// Returns the valve ID with its name or create a new ID.
fn valve_id_new(&mut self, name: &str) -> u8 {
let next_id = self.valves.len() as u8;
assert!(next_id <= 127);
*self.valves.entry(name.to_string()).or_insert(next_id)
}
/// Returns the valve ID with its name. Valve must exist.
fn valve_id(&self, name: &str) -> u8 {
*self.valves.get(name).unwrap()
}
/// Returns the valve name with its ID. Used only in `show()`.
fn valve_name(&self, valve_id: u8) -> &str {
self.valves.iter().find(|x| *x.1 == valve_id).unwrap().0
}
/// Show the network of pipes (puzzle input), up the order to the valves.
fn show(&self) {
for (name, id) in &self.valves {
let remotes = (self.tunnels[id]
.iter()
.map(|x| self.valve_name(*x))
.collect::<Vec<&str>>())
.join(", ");
if self.tunnels[id].len() == 1 {
println!(
"Valve {} has flow rate={}; tunnel leads to valve {}",
name,
self.flow_rates.get(id).unwrap_or(&0),
remotes
);
} else {
println!(
"Valve {} has flow rate={}; tunnels lead to valves {}",
name,
self.flow_rates.get(id).unwrap_or(&0),
remotes
);
}
}
}
/// Recursively search for the best flow rate.
fn max_flow(
&self,
valve: u8,
opened: u128,
time_left: u32,
seen: &mut HashMap<(u8, u128, u32), u32>,
) -> u32 {
if let Some(e) = seen.get(&(valve, opened, time_left)) {
return *e;
}
if time_left <= 1 {
return 0;
}
let mut best = 0;
if (opened & (1u128 << valve)) == 0 {
if let Some(flow) = self.flow_rates.get(&valve) {
best = (time_left - 1) * flow
+ self.max_flow(valve, opened | (1u128 << valve), time_left - 1, seen);
}
}
best = best.max(
self.tunnels[&valve]
.iter()
.map(|x| self.max_flow(*x, opened, time_left - 1, seen))
.max()
.unwrap(),
);
seen.insert((valve, opened, time_left), best);
best
}
// Solves part one
fn part1(&self) -> u32 {
let mut seen = HashMap::new();
self.max_flow(self.valve_id("AA"), 0, 30, &mut seen)
}
// Solve part two
fn part2(&self) -> u32 {
let start_valve = self.valve_id("AA");
let mut best = 0;
// make two lists of distinct valves to open by me or the elephant
// the lists are bitfields of valve ID actually
// (note: me and elephant are interchangeable, hence the -1: there are twice less partitions)
let partitions = 1u32 << (self.flow_rates.len() - 1);
for partition in 0..partitions {
// bit value 1 is for me
let me: u128 = self
.flow_rates
.iter()
.enumerate()
.filter(|(bit, _)| (partition & (1 << bit) != 0))
.map(|(_, (valve, _))| 1u128 << *valve)
.sum();
// bit value 0 is for the elehant
let elephant: u128 = self
.flow_rates
.iter()
.enumerate()
.filter(|(bit, _)| (partition & (1 << bit) == 0))
.map(|(_, (valve, _))| 1u128 << *valve)
.sum();
let best_me = self.max_flow_valves(start_valve, 26, me);
let best_elephant = self.max_flow_valves(start_valve, 26, elephant);
best = best.max(best_me + best_elephant);
}
best
}
fn max_flow_valves(&self, valve: u8, time_left: u32, nodes: u128) -> u32 {
if time_left <= 1 {
return 0;
}
let mut best = 0; // max flow for the set of nodes
let mut node = 0u8; // dest valve ID
let mut nodes_bitfield = nodes; // excessively complicated, I admit
while nodes_bitfield != 0 {
if nodes_bitfield & 1 == 1 {
// i.e. nodes has the bit 'node' set
let time_dist = self.distance(valve, node);
assert_ne!(time_dist, 0);
if time_left - 1 > time_dist {
let time = time_left - 1 - time_dist;
best = best.max(
time * self.flow_rates[&node]
+ self.max_flow_valves(node, time, nodes & !(1u128 << node)),
);
}
}
nodes_bitfield /= 2;
node += 1;
}
best
}
}
/// main function
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(&args.path);
if args.verbose {
puzzle.show();
}
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 1651);
}
#[test]
fn test_part2() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 1707);
}
}