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
|
mod stuff;
use std::collections::{HashMap};
use crate::stuff::{ascii_to_u64, is_all_ascii_ws, read_helper, Direction, Node};
pub const START: Node = [b'A', b'A', b'A'];
pub const FINISH: Node = [b'Z', b'Z', b'Z'];
fn main() {
let mut stdin = std::io::stdin().lock();
let mut buf: Vec<u8> = Vec::new();
let num_bytes = read_helper(&mut stdin, &mut buf, b'\n').expect("IO error");
if num_bytes == 0 { panic!("Malformed input"); }
let instructions: Vec<Direction> = (& buf).into_iter()
.map(|& c| Direction::try_from(c).expect("Malformed input"))
.collect();
let num_bytes = read_helper(&mut stdin, &mut buf, b'\n').expect("IO error");
assert!(is_all_ascii_ws(& buf));
let mut nodes: HashMap<Node, (Node, Node)> = HashMap::new();
loop {
let num_bytes = read_helper(&mut stdin, &mut buf, b'=').expect("IO error");
if num_bytes == 0 { break; }
let node: Node = core::array::from_fn(|i| buf[i]);
let num_bytes = read_helper(&mut stdin, &mut buf, b',').expect("IO error");
if num_bytes == 0 { panic!("Malformed input"); }
let node_l: Node = core::array::from_fn(|i| buf[2+i]);
let num_bytes = read_helper(&mut stdin, &mut buf, b'\n').expect("IO error");
if num_bytes == 0 { panic!("Malformed input"); }
let node_r: Node = core::array::from_fn(|i| buf[1+i]);
nodes.insert(node, (node_l, node_r));
}
let mut node: Node = START;
for (i, instruction) in instructions.into_iter().cycle().enumerate() {
if node == FINISH {
println!("{}", i);
break;
}
let (left, right) = nodes.get(& node).expect("Non-existent node");
match instruction {
Direction::L => { node = *left; },
Direction::R => { node = *right; }
}
}
}
|