From 7bb2b390a0cb0a26d9f41c253bae13734e51daec Mon Sep 17 00:00:00 2001 From: Russell Champoux Date: Thu, 4 Dec 2025 16:05:29 +0000 Subject: [PATCH] day 03 --- data/examples/03.txt | 4 +++ src/bin/03.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++ src/template.txt | 1 + 3 files changed, 73 insertions(+) create mode 100644 data/examples/03.txt create mode 100644 src/bin/03.rs diff --git a/data/examples/03.txt b/data/examples/03.txt new file mode 100644 index 0000000..7255fca --- /dev/null +++ b/data/examples/03.txt @@ -0,0 +1,4 @@ +987654321111111 +811111111111119 +234234234234278 +818181911112111 diff --git a/src/bin/03.rs b/src/bin/03.rs new file mode 100644 index 0000000..ed336fc --- /dev/null +++ b/src/bin/03.rs @@ -0,0 +1,68 @@ +advent_of_code::solution!(3); + +fn get_largest_battery(battery: &[u32], start_idx: usize, end_idx: usize) -> Option<(u32, usize)> { + let mut largest = battery[start_idx]; + let mut largest_idx = start_idx; + for i in start_idx..=end_idx { + if battery[i] > largest { + largest = battery[i]; + largest_idx = i; + } + } + Some((largest, largest_idx)) +} + +fn get_joltage(line: &str, desired_digits: u8) -> Option { + let all_values = line.chars().into_iter().map(|c| c.to_digit(10).unwrap()).collect::>(); + // determine the largest joltage by finding the largest battery in the list (excluding the last item) and then the largest battery after that + let mut total: u64 = 0; + let mut start_idx = 0; + + // print!("Calculating joltage for line: {} -> ", line); + for i in 1..=desired_digits { + let end_idx = all_values.len() - (1 + desired_digits - i) as usize; + // print!("Finding largest between {} and {}", start_idx, end_idx); + let (largest, largest_idx) = get_largest_battery(&all_values, start_idx, end_idx).unwrap(); + // println!(" -> found {}", largest); + total = total * 10 + largest as u64; + start_idx = largest_idx + 1; + } + Some(total) +} + +pub fn part_one(input: &str) -> Option { + let mut total: u64 = 0; + for line in input.split('\n').filter(|l| !l.is_empty()) { + total += get_joltage(line, 2).unwrap(); + } + + println!("Total: {}", total); + Some(total) +} + +pub fn part_two(input: &str) -> Option { + let mut total: u64 = 0; + for line in input.split('\n').filter(|l| !l.is_empty()) { + total += get_joltage(line, 12).unwrap(); + } + + println!("Total: {}", total); + Some(total) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_part_one() { + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(357)); + } + + #[test] + fn test_part_two() { + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); + assert_eq!(result, Some(3121910778619)); + } +} diff --git a/src/template.txt b/src/template.txt index 87eac99..c53d29b 100644 --- a/src/template.txt +++ b/src/template.txt @@ -1,4 +1,5 @@ advent_of_code::solution!(%DAY_NUMBER%); +use itertools::Itertools; pub fn part_one(input: &str) -> Option { None