From 562768449425cf66eb786f942bf5add57d18e846 Mon Sep 17 00:00:00 2001 From: Luke Else Date: Fri, 8 Dec 2023 16:23:24 +0000 Subject: [PATCH] Day 08 Part 2 complete :) Very efficient solution --- src/solutions/day08.rs | 16 +++++++++++----- src/utils.rs | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/solutions/day08.rs b/src/solutions/day08.rs index 5bc5c4b..da037d2 100644 --- a/src/solutions/day08.rs +++ b/src/solutions/day08.rs @@ -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, ) -> Result> { @@ -105,7 +111,7 @@ impl Day08 { continue; } } - if next.ends_with("ZZZ") { + if next.ends_with(end) { found = true; break; } diff --git a/src/utils.rs b/src/utils.rs index fbe3c16..860be43 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -33,3 +33,27 @@ pub fn get_input(day: u8, input: InputType) -> Result, Box 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; + } +}