Day 08 Part 2 complete :) Very efficient solution

This commit is contained in:
Luke Else 2023-12-08 16:23:24 +00:00
parent 4a095e2a74
commit 5627684494
2 changed files with 35 additions and 5 deletions

View File

@ -1,5 +1,7 @@
use std::collections::HashMap;
use crate::utils::{self};
use super::Solution;
pub struct Day08 {}
@ -38,14 +40,17 @@ impl Solution for Day08 {
}
}
let mut count = 0u32;
let mut count = vec![];
println!("{:?}", start_points);
for start in start_points {
count += self.traverse_to_end(&start, &"Z".to_owned(), &instructions, &map)?
count.push(self.traverse_to_end(&start, &"Z".to_owned(), &instructions, &map)?);
}
Ok(Box::new(count))
let lcm = count
.iter()
.fold(1u64, |acc, x| -> u64 { utils::lcm(acc, *x as u64) });
Ok(Box::new(lcm))
}
fn get_day(&self) -> u8 {
@ -87,6 +92,7 @@ impl Day08 {
&self,
start: &String,
end: &String,
// detect_cycles: bool,
instructions: &String,
map: &HashMap<String, (String, String)>,
) -> Result<u32, Box<dyn std::error::Error>> {
@ -105,7 +111,7 @@ impl Day08 {
continue;
}
}
if next.ends_with("ZZZ") {
if next.ends_with(end) {
found = true;
break;
}

View File

@ -33,3 +33,27 @@ pub fn get_input(day: u8, input: InputType) -> Result<Vec<String>, Box<dyn Error
Ok(data)
}
pub fn lcm(first: u64, second: u64) -> u64 {
first * second / gcd(first, second)
}
pub fn gcd(first: u64, second: u64) -> u64 {
let mut max = first;
let mut min = second;
if min > max {
let val = max;
max = min;
min = val;
}
loop {
let res = max % min;
if res == 0 {
return min;
}
max = min;
min = res;
}
}