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