This commit is contained in:
Acvaxoort
2023-12-08 14:00:33 +01:00
parent 5a03581041
commit d2db596bae
4 changed files with 874 additions and 0 deletions

45
day8/src/main.rs Normal file
View File

@@ -0,0 +1,45 @@
use std::fs::read_to_string;
use std::collections::HashMap;
use num::integer::lcm;
fn get_steps_to(directions: &str, nodes: &HashMap<&str, (&str, &str)>,
start: &str, stop: fn(&str) -> bool) -> u64 {
let mut current_node = start;
let mut counter: u64 = 0;
'outer: loop {
for c in directions.bytes() {
let (left, right) = nodes[current_node];
match c {
b'L' => current_node = left,
b'R' => current_node = right,
_ => {}
}
counter += 1;
if stop(current_node) {
break 'outer;
}
}
}
counter
}
fn main() {
let lines_str = read_to_string("input.txt").unwrap();
let mut lines_iter = lines_str.lines();
let directions = lines_iter.next().unwrap();
lines_iter.next();
let mut nodes: HashMap<&str, (&str, &str)> = HashMap::new();
for line in lines_iter {
let mut ids = line.split([' ', '(', ')', '=', ',']).filter(|&str| !str.is_empty());
nodes.insert(ids.next().unwrap(), (ids.next().unwrap(), ids.next().unwrap()));
}
let counter1 = get_steps_to(directions, &nodes, "AAA", |str| str == "ZZZ");
let counter2 = nodes.iter()
.filter_map(|(&id, _)|
Some(id).filter(|&id| id.as_bytes()[2 as usize] == b'A'))
.map(|node| get_steps_to(
directions, &nodes, node, |str| str.as_bytes()[2 as usize] == b'Z'))
.fold(1 as u64, |acc, counter| lcm(acc, counter));
println!("{}", counter1);
println!("{}", counter2);
}