70 lines
1.7 KiB
Rust
70 lines
1.7 KiB
Rust
use std::collections::HashMap;
|
|
|
|
use crate::utils::input_reader;
|
|
|
|
pub struct Node {
|
|
pub value: String,
|
|
pub left: String,
|
|
pub right: String,
|
|
}
|
|
|
|
pub fn part_one() -> String {
|
|
if let Ok(lines) = input_reader::read_lines("./input/2023/day_08/input.txt") {
|
|
let mut node_map: HashMap<String, Node> = HashMap::new();
|
|
let mut instructions: Vec<char> = Vec::new();
|
|
let mut s: String;
|
|
|
|
for (i, line) in lines.enumerate() {
|
|
s = line.unwrap();
|
|
|
|
if i == 0 {
|
|
instructions = s.chars().collect();
|
|
continue;
|
|
}
|
|
|
|
if s.is_empty() {
|
|
continue;
|
|
}
|
|
|
|
let node = parse_line(&s);
|
|
node_map.insert(node.value.clone(), node);
|
|
}
|
|
|
|
let mut curr = &node_map["AAA"];
|
|
let mut count = 0;
|
|
|
|
while curr.value != "ZZZ" {
|
|
let i = count % instructions.len();
|
|
|
|
if instructions[i] == 'L' {
|
|
curr = &node_map[&curr.left];
|
|
} else if instructions[i] == 'R' {
|
|
curr = &node_map[&curr.right];
|
|
}
|
|
|
|
count += 1;
|
|
}
|
|
|
|
return count.to_string();
|
|
} else {
|
|
panic!("Failed to read lines from input file");
|
|
}
|
|
}
|
|
|
|
pub fn parse_line(s: &str) -> Node {
|
|
// AAA = (BBB, CCC)
|
|
let s1: Vec<&str> = s.split('=').collect();
|
|
let node_val = s1[0].trim();
|
|
|
|
let s2 = s1[1].replace(&['(', ')'], "");
|
|
let s3: Vec<&str> = s2.trim().split(',').collect();
|
|
let node_left = s3[0].trim();
|
|
let node_right = s3[1].trim();
|
|
|
|
Node {
|
|
value: node_val.to_string(),
|
|
left: node_left.to_string(),
|
|
right: node_right.to_string(),
|
|
}
|
|
}
|