Fix day 1 to work with our harness.

This commit is contained in:
Anna Rose 2024-02-15 17:57:00 +00:00
parent 64fd4e99c4
commit f2caf1d0cb
3 changed files with 9 additions and 19 deletions

2
2022/Cargo.lock generated
View File

@ -3,7 +3,7 @@
version = 3
[[package]]
name = "day01"
name = "aoc2022"
version = "0.1.0"
dependencies = [
"sorted-vec",

View File

@ -1,5 +1,5 @@
[package]
name = "2022"
name = "aoc2022"
version = "0.1.0"
edition = "2021"

View File

@ -1,4 +1,3 @@
use std::env;
use std::io;
use std::io::prelude::*;
use std::fs::File;
@ -9,14 +8,7 @@ fn read_lines(filename: &str) -> io::Result<io::Lines<io::BufReader<File>>> {
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) {
fn update_max(max: &mut SortedVec<i32>, current: i32) {
if max.is_empty() {
max.insert(current);
return
@ -24,15 +16,10 @@ fn update_max(max: &mut SortedVec<i32>, current: i32, step: i32) {
if current <= max[0] { return }
max.insert(current);
match step {
2 => { if max.len() > 3 { max.remove_index(0); } },
_ => { max.remove_index(0); },
}
if max.len() > 3 { 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;
@ -41,12 +28,15 @@ pub fn execute() -> Result<(), io::Error> {
current = match text.parse::<i32>() {
Ok(value) => current + value,
Err(_) => {
update_max(&mut max, current, step);
update_max(&mut max, current);
0
},
}
}
println!("{}", max.iter().fold(0i32, |sum, i| sum + (*i as i32)));
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(())
}