From 7a90ec700dc1cc18e1824101ff88b2ae9b700769 Mon Sep 17 00:00:00 2001 From: Burnus Date: Fri, 12 May 2023 16:29:54 +0200 Subject: [PATCH] Cleanup for 2022 day 1: Turned into a lib and introduced parse errors instead of silently defaulting to 0 --- 2022/day01-calorie_counting/src/lib.rs | 41 +++++++++++++++++++++ 2022/day01-calorie_counting/src/main.rs | 47 ------------------------- 2 files changed, 41 insertions(+), 47 deletions(-) create mode 100644 2022/day01-calorie_counting/src/lib.rs delete mode 100644 2022/day01-calorie_counting/src/main.rs diff --git a/2022/day01-calorie_counting/src/lib.rs b/2022/day01-calorie_counting/src/lib.rs new file mode 100644 index 0000000..8ea7f56 --- /dev/null +++ b/2022/day01-calorie_counting/src/lib.rs @@ -0,0 +1,41 @@ +use std::num::ParseIntError; + +fn try_parse_cal_list(list: &str) -> Result, ParseIntError> { + let mut cals: Vec<_> = list.split("\n\n") + .collect::>() + .iter() + .map(|individual_list| individual_list.lines() + .map(|n| n.parse::()) + .sum::>()) + .collect::, _>>()?; + + cals.sort_by_key(|i| std::cmp::Reverse(*i)); + Ok(cals) +} + +pub fn run(input: &str) -> Result<(usize, usize), ParseIntError> { + let elves = try_parse_cal_list(input)?; + Ok((elves[0], elves.iter().take(3).sum::())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn read_file(path: &str) -> String { + std::fs::read_to_string(path) + .expect("File not Found") + } + + #[test] + fn sample_input() { + let list = read_file("tests/sample_input"); + assert_eq!(run(&list), Ok((24000, 45000))); + } + + #[test] + fn challenge_input() { + let list = read_file("tests/input"); + assert_eq!(run(&list), Ok((71780, 212489))); + } +} diff --git a/2022/day01-calorie_counting/src/main.rs b/2022/day01-calorie_counting/src/main.rs deleted file mode 100644 index 9a9626e..0000000 --- a/2022/day01-calorie_counting/src/main.rs +++ /dev/null @@ -1,47 +0,0 @@ -use std::fs; - -fn parse_cal_list(list: String) -> Vec { - let mut cals: Vec = list.split("\n\n") - .collect::>() - .iter() - .map(|individual_list| individual_list.lines() - .map(|n| n.parse::().unwrap_or(0)) - .sum::()) - .collect(); - - cals.sort(); - cals.reverse(); - cals -} - -fn main() { - let list = read_file("input"); - - let elves = parse_cal_list(list); - - println!("Max: {}", elves[0]); - println!("Top 3: {}", elves.iter().take(3).sum::()) -} - -fn read_file(path: &str) -> String { - fs::read_to_string(path) - .expect("File not Found") -} - -#[test] -fn sample_input() { - let list = read_file("tests/sample_input"); - let elves = parse_cal_list(list); - - assert_eq!(elves[0], 24000); - assert_eq!(elves.iter().take(3).sum::(), 45000); -} - -#[test] -fn challenge_input() { - let list = read_file("tests/input"); - let elves = parse_cal_list(list); - - assert_eq!(elves[0], 71780); - assert_eq!(elves.iter().take(3).sum::(), 212489); -}