2023-08: Solve part two

This commit is contained in:
Mathis 2023-12-20 21:43:31 +01:00
parent ce170f04ff
commit bd64b811b9
1 changed files with 36 additions and 28 deletions

View File

@ -4,9 +4,9 @@ use crate::utils::input_reader;
use crate::year_2023::day_08_haunted_wasteland::common::{parse_line, Node}; use crate::year_2023::day_08_haunted_wasteland::common::{parse_line, Node};
pub fn part_two() -> String { pub fn part_two() -> String {
if let Ok(lines) = input_reader::read_lines("./input/2023/day_08/input_test_part_2.txt") { 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 node_map: HashMap<String, Node> = HashMap::new();
let mut start_nodes: Vec<&Node> = Vec::new(); let mut start_nodes: Vec<String> = Vec::new();
let mut instructions: Vec<char> = Vec::new(); let mut instructions: Vec<char> = Vec::new();
let mut s: String; let mut s: String;
@ -25,48 +25,56 @@ pub fn part_two() -> String {
let node = parse_line(&s); let node = parse_line(&s);
let value = node.value.clone(); let value = node.value.clone();
node_map.insert(value.clone(), &node.clone()); node_map.insert(value.clone(), node);
if value.ends_with('A') { if value.ends_with('A') {
let cloned_node = node.clone(); start_nodes.push(value.clone())
start_nodes.push(&cloned_node);
} }
} }
let mut curr_nodes: Vec<&Node> = start_nodes; let mut counts: Vec<usize> = Vec::new();
let mut count = 0;
let mut cond = true;
while cond { for curr in start_nodes {
let i = count % instructions.len();
let c = instructions[i];
let mut new_curr: Vec<&Node> = Vec::new(); let mut curr_node = &node_map[&curr];
cond = false; let mut count = 0;
while !curr_node.value.ends_with('Z') {
let i = count % instructions.len();
for n in curr_nodes {
let nn: &Node;
if instructions[i] == 'L' { if instructions[i] == 'L' {
nn = &node_map[&n.left]; curr_node = &node_map[&curr_node.left];
} else if instructions[i] == 'R' { } else if instructions[i] == 'R' {
nn = &node_map[&n.right]; curr_node = &node_map[&curr_node.right];
} else {
panic!("Unknown instruction!")
} }
if !nn.value.clone().ends_with('Z') { count += 1;
cond = true;
}
new_curr.push(nn);
} }
curr_nodes = new_curr; counts.push(count);
count += 1;
} }
return count.to_string(); let result = counts.iter().fold(1, |acc, &x| lcm(acc, x));
return result.to_string();
} else { } else {
panic!("Failed to read lines from input file"); panic!("Failed to read lines from input file");
} }
} }
fn lcm(a : usize, b : usize) -> usize {
a * b / gcd(a, b)
}
fn gcd(a : usize, b : usize) -> usize {
if b > a {
return gcd(b, a);
}
if b == 0 {
a
} else {
gcd(b, a % b)
}
}