adventofcode/2022/day01/src/main.rs

53 lines
1.2 KiB
Rust

use std::env;
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 get_step() -> i32 {
for arg in env::args() {
if arg == "2" { return 2 }
}
return 1
}
fn update_max(max: &mut SortedVec<i32>, current: i32, step: i32) {
if max.is_empty() {
max.insert(current);
return
}
if current <= max[0] { return }
max.insert(current);
match step {
2 => { if max.len() > 3 { max.remove_index(0); } },
_ => { max.remove_index(0); },
}
}
fn main() -> Result<(), io::Error> {
let step = get_step();
let mut max: SortedVec<i32> = SortedVec::new();
let mut current = 0;
for line in read_lines("input.txt")? {
let text = line?;
current = match text.parse::<i32>() {
Ok(value) => current + value,
Err(_) => {
update_max(&mut max, current, step);
0
},
}
}
println!("{}", max.iter().fold(0i32, |sum, i| sum + (*i as i32)));
Ok(())
}