43 lines
1.1 KiB
Rust
43 lines
1.1 KiB
Rust
use std::io;
|
|
use std::io::prelude::*;
|
|
use std::fs::File;
|
|
use sorted_vec::SortedVec;
|
|
|
|
fn read_lines(filename: &str) -> io::Result<io::Lines<io::BufReader<File>>> {
|
|
let file = File::open(filename)?;
|
|
Ok(io::BufReader::new(file).lines())
|
|
}
|
|
|
|
fn update_max(max: &mut SortedVec<i32>, current: i32) {
|
|
if max.is_empty() {
|
|
max.insert(current);
|
|
return
|
|
}
|
|
if current <= max[0] { return }
|
|
|
|
max.insert(current);
|
|
if max.len() > 3 { max.remove_index(0); }
|
|
}
|
|
|
|
pub fn execute() -> Result<(), io::Error> {
|
|
let mut max: SortedVec<i32> = SortedVec::new();
|
|
let mut current = 0;
|
|
|
|
for line in read_lines("input/day01.txt")? {
|
|
let text = line?;
|
|
current = match text.parse::<i32>() {
|
|
Ok(value) => current + value,
|
|
Err(_) => {
|
|
update_max(&mut max, current);
|
|
0
|
|
},
|
|
}
|
|
}
|
|
|
|
if let Some(x) = max.iter().last() {
|
|
println!("Step 1 solution: {x}");
|
|
}
|
|
println!("Step 2 solution: {}", max.iter().fold(0i32, |sum, i| sum + (*i as i32)));
|
|
Ok(())
|
|
}
|