From e18c62168b17557e8106cbca1197af47127330d9 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Mon, 5 Dec 2022 20:17:33 +0100 Subject: Add day 1 for 2022 --- 2022/day1/src/lib.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 2022/day1/src/lib.rs (limited to '2022/day1/src') diff --git a/2022/day1/src/lib.rs b/2022/day1/src/lib.rs new file mode 100644 index 0000000..26df697 --- /dev/null +++ b/2022/day1/src/lib.rs @@ -0,0 +1,72 @@ +pub fn get_sums(input: &str) -> Vec { + let groups: Vec<&str> = input.split("\n\n").collect::>(); + let data_groups = groups + .into_iter() + .map(|x| { + let numbers: i32 = x + .split('\n') + .map(|x| x.parse::().unwrap_or_default()) + .sum(); + + return numbers; + }) + .collect::>(); + + data_groups +} + +pub fn part1(input: &str) -> i32 { + let sums = get_sums(input); + + sums.into_iter().max().unwrap() +} + +pub fn part2(input: &str) -> i32 { + let mut sums = get_sums(input); + + sums.sort(); + sums.reverse(); + + sums[0] + sums[1] + sums[2] +} + +#[cfg(test)] +mod day1_tests { + use super::*; + + #[test] + fn test_example() { + let data = include_str!("../example.txt"); + + let result = part1(data); + + assert_eq!(result, 24000); + } + + #[test] + fn test_input() { + let data = include_str!("../input.txt"); + + let result = part1(data); + + assert_eq!(result, 69912); + } + + #[test] + fn test_example_part2() { + let data = include_str!("../example.txt"); + + let result = part2(data); + + assert_eq!(result, 45000); + } + + #[test] + fn test_input_part2() { + let data = include_str!("../input.txt"); + + let result = part2(data); + + assert_eq!(result, 208180); + } +} -- cgit v1.2.3-18-g5258