Skip to content

Commit

Permalink
refactor: move LCM func to public mod
Browse files Browse the repository at this point in the history
  • Loading branch information
jhrcook committed Jan 16, 2024
1 parent 8429095 commit ad415c5
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 14 deletions.
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod data;
mod math_utils;
pub mod solutions;

use thiserror::Error;

#[derive(Error, Debug)]
Expand Down
10 changes: 10 additions & 0 deletions src/math_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use num::integer;

// Algorithm source: https://www.geeksforgeeks.org/lcm-of-given-array-elements/
pub fn lcm(a: Vec<u64>) -> u64 {
let mut lcm = a[0];
for i in a.iter() {
lcm = integer::div_floor(lcm * *i, integer::gcd(lcm, *i));
}
lcm
}
18 changes: 4 additions & 14 deletions src/solutions/day08.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -193,15 +193,6 @@ fn make_state_map(
}
}

// Algorithm source: https://www.geeksforgeeks.org/lcm-of-given-array-elements/
fn lcm(a: Vec<u64>) -> 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<u64, PuzzleErr> {
let (directions, graph) = parse_input(input)?;

Expand All @@ -224,10 +215,9 @@ pub fn puzzle_2(input: &str) -> Result<u64, PuzzleErr> {
.map(|n| make_state_map(n, &end_nodes, &graph, directions.clone()))
.collect::<Vec<_>>();

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) {
Expand Down

0 comments on commit ad415c5

Please sign in to comment.