-
Notifications
You must be signed in to change notification settings - Fork 1
/
15b.rs
282 lines (264 loc) · 8.95 KB
/
15b.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
274
275
276
277
278
279
280
281
282
use std::sync::mpsc;
use std::collections::{VecDeque, HashMap, HashSet};
fn interpret(mem: &mut Vec<i64>,
read_input: &mut dyn FnMut() -> i64,
write_output: &mut dyn FnMut(i64)) {
#[derive(PartialEq, Debug)]
enum AddrMode {
POSITION,
IMMEDIATE,
RELATIVE
}
fn read_direct(mem: &[i64], pos: usize) -> i64 {
if pos >= mem.len() {
0
}
else {
mem[pos]
}
}
fn mem_follow_mode(val: i64, mem: &[i64], relbase: usize, mode: AddrMode)
-> i64 {
match mode {
AddrMode::POSITION => read_direct(mem, val as usize),
AddrMode::IMMEDIATE => val,
AddrMode::RELATIVE => read_direct(mem, (relbase as i64 + val) as usize),
}
}
fn mem_read(mem: &[i64], pos: usize, relbase: usize, mode: AddrMode) -> i64 {
mem_follow_mode(read_direct(mem, pos), mem, relbase, mode)
}
fn decode_mode(digit: i64) -> AddrMode {
match digit {
0 => AddrMode::POSITION,
1 => AddrMode::IMMEDIATE,
2 => AddrMode::RELATIVE,
other => panic!("invalid opcode {}", other),
}
}
fn decode_next(mem: &mut [i64], pos: usize, relbase: usize, modes: i64) -> (i64, i64) {
(mem_read(mem, pos, relbase, decode_mode(modes % 10)),
modes / 10)
}
fn decode_operands_1(mem: &mut [i64], pos: usize, relbase: usize) -> (i64, i64) {
let modes = mem[pos] / 100;
decode_next(mem, pos + 1, relbase, modes)
}
fn decode_operands_2(mem: &mut [i64], pos: usize, relbase: usize) -> (i64, i64, i64) {
let modes = mem[pos] / 100;
let (val1, modes) = decode_next(mem, pos + 1, relbase, modes);
let (val2, modes) = decode_next(mem, pos + 2, relbase, modes);
(val1, val2, modes)
}
fn mem_write(mem: &mut Vec<i64>, relbase: usize,
raw_addr: i64, mode: AddrMode, val: i64) {
assert_ne!(mode, AddrMode::IMMEDIATE);
let pos = if let AddrMode::RELATIVE = mode {
(raw_addr as isize + relbase as isize) as usize
}
else {raw_addr as usize};
if pos >= mem.len() {
mem.extend(std::iter::repeat(0).take(pos - mem.len() + 1));
}
mem[pos] = val;
}
let mut pos = 0usize;
let mut relbase = 0usize;
while mem[pos] != 99 {
match mem[pos] % 100 {
1 => {
let (op1, op2, write_mode_raw) = decode_operands_2(mem, pos, relbase);
let val = op1.checked_add(op2)
.expect(&format!("overflow {}+{}", op1, op2));
mem_write(mem, relbase, mem[pos + 3], decode_mode(write_mode_raw), val);
pos += 4;
}
2 => {
let (op1, op2, write_mode_raw) = decode_operands_2(mem, pos, relbase);
let val = op1.checked_mul(op2)
.expect(&format!("overflow {}*{}", op1, op2));
mem_write(mem, relbase, mem[pos + 3], decode_mode(write_mode_raw), val);
pos += 4;
}
3 => {
let write_mode = decode_mode(mem[pos] / 100);
let val = read_input();
mem_write(mem, relbase, mem[pos + 1], write_mode, val);
pos += 2;
}
4 => {
let (val, modes) = decode_operands_1(mem, pos, relbase);
assert_eq!(modes, 0);
write_output(val);
pos += 2;
}
5 => {
let (op1, op2, modes) = decode_operands_2(mem, pos, relbase);
assert_eq!(modes, 0);
if op1 != 0 {
pos = op2 as usize;
}
else {
pos += 3;
}
}
6 => {
let (op1, op2, modes) = decode_operands_2(mem, pos, relbase);
assert_eq!(modes, 0);
if op1 == 0 {
pos = op2 as usize;
}
else {
pos += 3;
}
}
7 => {
let (op1, op2, write_mode_raw) = decode_operands_2(mem, pos, relbase);
let val = if op1 < op2 {1} else {0};
mem_write(mem, relbase, mem[pos + 3],
decode_mode(write_mode_raw), val);
pos += 4;
}
8 => {
let (op1, op2, write_mode_raw) = decode_operands_2(mem, pos, relbase);
let val = if op1 == op2 {1} else {0};
mem_write(mem, relbase, mem[pos + 3],
decode_mode(write_mode_raw), val);
pos += 4;
}
9 => {
let (val, modes) = decode_operands_1(mem, pos, relbase);
assert_eq!(modes, 0);
relbase = (relbase as isize + val as isize) as usize;
pos += 2;
}
other => panic!("invalid instruction {}", other),
};
}
}
fn reverse_step(step: i64) -> i64 {
match step {
1 => 2,
2 => 1,
3 => 4,
4 => 3,
_ => unreachable!(),
}
}
fn apply_step(pos: (i32, i32), step: i64) -> (i32, i32) {
match step {
1 => (pos.0, pos.1 - 1),
2 => (pos.0, pos.1 + 1),
3 => (pos.0 - 1, pos.1),
4 => (pos.0 + 1, pos.1),
_ => unreachable!(),
}
}
fn explore(program: &[i64]) -> (HashMap<(i32, i32), bool>, Option<(i32, i32)>) {
let (in_tx, in_rx) = mpsc::channel();
let (out_tx, out_rx) = mpsc::channel();
let thr = {
let program = program.to_vec();
std::thread::spawn(
move ||
interpret(&mut program.to_vec(),
&mut || in_rx.recv().unwrap(),
&mut |val| out_tx.send(val).unwrap())
)
};
let mut target_pos = None;
let mut map = HashMap::new();
let mut todo = VecDeque::new();
todo.push_back(vec![]);
while let Some(path) = todo.pop_front() {
let mut current_pos: (i32, i32) = (0, 0);
for &old_step in &path {
in_tx.send(old_step).unwrap();
current_pos = apply_step(current_pos, old_step);
}
for _ in 0..path.len() {
match out_rx.recv().unwrap() {
1|2 => (),
_ => panic!("wrong response")
}
}
for &new_step in &[1, 2, 3, 4] {
if let Some(_) = map.get(&apply_step(current_pos, new_step)) {
continue;
}
in_tx.send(new_step).unwrap();
let is_wall = match out_rx.recv().unwrap() {
0 => true,
1 => false,
2 => {
target_pos = Some(apply_step(current_pos, new_step));
false
}
_ => unreachable!(),
};
map.insert(apply_step(current_pos, new_step), is_wall);
if is_wall {
continue;
}
in_tx.send(reverse_step(new_step)).unwrap();
match out_rx.recv().unwrap() {
1|2 => (),
_ => panic!("wrong response")
}
let mut new_path = path.clone();
new_path.push(new_step);
todo.push_back(new_path);
}
for &old_step in path.iter().rev() {
in_tx.send(reverse_step(old_step)).unwrap();
}
for _ in 0..path.len() {
match out_rx.recv().unwrap() {
1|2 => (),
_ => panic!("wrong response")
}
}
}
let old_hook = std::panic::take_hook();
// prevent panic output when channel recv() panics
std::panic::set_hook(Box::new(|_| ()));
drop(in_tx);
drop(out_rx);
let _ = thr.join();
std::panic::set_hook(old_hook);
(map, target_pos)
}
fn flood(map: &HashMap<(i32, i32), bool>, start_pos: (i32, i32)) -> usize {
let mut final_time = 0;
let mut visited = HashSet::new();
let mut advance = VecDeque::new();
advance.push_back((0usize, start_pos));
while let Some((timecnt, pos)) = advance.pop_front() {
final_time = timecnt;
for &step in &[1, 2, 3, 4] {
let newpos = apply_step(pos, step);
let &is_wall = map.get(&newpos).unwrap();
if is_wall {
continue;
}
if !visited.insert(newpos) {
continue;
}
advance.push_back((timecnt + 1, newpos));
}
}
final_time
}
fn read_prog(input: &[u8]) -> Vec<i64> {
let input = std::str::from_utf8(input).unwrap();
let mut ret = vec![];
for tok in input.split(",") {
ret.push(tok.trim().parse().unwrap());
}
ret
}
fn main() {
let prog = read_prog(include_bytes!("15.input"));
let (map, flood_start_pos) = explore(&prog);
println!("{:?}", flood(&map, flood_start_pos.unwrap()));
}