From ad415c5f7002b21a3ae19a272c3d3bab18b192b7 Mon Sep 17 00:00:00 2001 From: Joshua Cook Date: Tue, 16 Jan 2024 06:56:10 -0500 Subject: [PATCH] refactor: move LCM func to public mod --- src/lib.rs | 2 ++ src/math_utils.rs | 10 ++++++++++ src/solutions/day08.rs | 18 ++++-------------- 3 files changed, 16 insertions(+), 14 deletions(-) create mode 100644 src/math_utils.rs diff --git a/src/lib.rs b/src/lib.rs index 9aae442..46ab22a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ mod data; +mod math_utils; pub mod solutions; + use thiserror::Error; #[derive(Error, Debug)] diff --git a/src/math_utils.rs b/src/math_utils.rs new file mode 100644 index 0000000..30a4e8d --- /dev/null +++ b/src/math_utils.rs @@ -0,0 +1,10 @@ +use num::integer; + +// Algorithm source: https://www.geeksforgeeks.org/lcm-of-given-array-elements/ +pub fn lcm(a: Vec) -> u64 { + let mut lcm = a[0]; + for i in a.iter() { + lcm = integer::div_floor(lcm * *i, integer::gcd(lcm, *i)); + } + lcm +} diff --git a/src/solutions/day08.rs b/src/solutions/day08.rs index 913a1aa..1eb067e 100644 --- a/src/solutions/day08.rs +++ b/src/solutions/day08.rs @@ -1,6 +1,6 @@ use crate::data::load; +use crate::math_utils; use lazy_static::lazy_static; -use num::integer::div_floor; use regex::Regex; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; @@ -193,15 +193,6 @@ fn make_state_map( } } -// Algorithm source: https://www.geeksforgeeks.org/lcm-of-given-array-elements/ -fn lcm(a: Vec) -> u64 { - let mut lcm = a[0]; - for i in a.iter() { - lcm = div_floor(lcm * *i, num::integer::gcd(lcm, *i)); - } - lcm -} - pub fn puzzle_2(input: &str) -> Result { let (directions, graph) = parse_input(input)?; @@ -224,10 +215,9 @@ pub fn puzzle_2(input: &str) -> Result { .map(|n| make_state_map(n, &end_nodes, &graph, directions.clone())) .collect::>(); - Ok(lcm(state_maps - .iter() - .map(|sm| sm.loop_size as u64) - .collect())) + Ok(math_utils::lcm( + state_maps.iter().map(|sm| sm.loop_size as u64).collect(), + )) } pub fn main(data_dir: &str) {