Move code into a single cargo module with an execution harness.

This commit is contained in:
2024-02-15 17:49:57 +00:00
parent 5b3a5d829d
commit 5bb3392691
7 changed files with 77 additions and 4 deletions

52
2022/src/day01.rs Normal file
View File

@ -0,0 +1,52 @@
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); },
}
}
pub fn execute() -> Result<(), io::Error> {
let step = get_step();
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, step);
0
},
}
}
println!("{}", max.iter().fold(0i32, |sum, i| sum + (*i as i32)));
Ok(())
}