diff options
Diffstat (limited to '08/src/part-1.rs')
-rw-r--r-- | 08/src/part-1.rs | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/08/src/part-1.rs b/08/src/part-1.rs new file mode 100644 index 0000000..bdfb409 --- /dev/null +++ b/08/src/part-1.rs @@ -0,0 +1,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; } + } + } +} |