1
0
Fork 0
AdvenOfCode2022/src/prob1/mod.rs

37 lines
1.1 KiB
Rust

use std::cmp::Reverse;
pub fn solve_part1(file_path: &str) -> i32 {
let mut max = 0;
let mut accumulated = 0;
std::fs::read_to_string(file_path)
.unwrap_or_else(|err| panic!("Please provide a text file as an argument: {err}"))
.lines()
.for_each(|number| {
if let Ok(yay) = number.parse::<i32>() {
accumulated += yay;
} else {
max = max.max(accumulated);
accumulated = 0;
}
});
max
}
pub fn solve_part2(file_path: &str) -> i32 {
let contents =
std::fs::read_to_string(file_path).expect("Please provide a text file as an argument.");
let lines: Vec<&str> = contents.split('\n').collect();
let mut numbers: Vec<i32> = Vec::with_capacity(lines.len());
let mut accumulated = 0;
lines.iter().for_each(|number| {
if let Ok(yay) = number.parse::<i32>() {
accumulated += yay;
} else {
numbers.push(accumulated);
accumulated = 0;
}
});
numbers.sort_by_key(|w| Reverse(*w));
numbers[0] + numbers[1] + numbers[2]
}