diff options
author | Santo Cariotti <santo@dcariotti.me> | 2022-12-05 20:17:33 +0100 |
---|---|---|
committer | Santo Cariotti <santo@dcariotti.me> | 2022-12-05 20:17:33 +0100 |
commit | e18c62168b17557e8106cbca1197af47127330d9 (patch) | |
tree | 574203ebd03843db4ca0265edecdd5f664175d42 /2022/day1/src | |
parent | cf6303a5bc1558ebdb7b467da38f74cd3ac3a9b1 (diff) |
Add day 1 for 2022
Diffstat (limited to '2022/day1/src')
-rw-r--r-- | 2022/day1/src/lib.rs | 72 |
1 files changed, 72 insertions, 0 deletions
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<i32> { + let groups: Vec<&str> = input.split("\n\n").collect::<Vec<&str>>(); + let data_groups = groups + .into_iter() + .map(|x| { + let numbers: i32 = x + .split('\n') + .map(|x| x.parse::<i32>().unwrap_or_default()) + .sum(); + + return numbers; + }) + .collect::<Vec<i32>>(); + + 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); + } +} |