From e04df4b548e28f0e590d45440475b1b315c8164d Mon Sep 17 00:00:00 2001 From: Anna Wiggins Date: Wed, 14 Feb 2024 20:04:34 +0000 Subject: [PATCH] Implement step 2 for day 1. --- 2022/day01/Cargo.lock | 9 +++++++++ 2022/day01/Cargo.toml | 1 + 2022/day01/src/main.rs | 33 +++++++++++++++++++++++++++++---- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/2022/day01/Cargo.lock b/2022/day01/Cargo.lock index 683c0b9..130e8e6 100644 --- a/2022/day01/Cargo.lock +++ b/2022/day01/Cargo.lock @@ -5,3 +5,12 @@ version = 3 [[package]] name = "day01" version = "0.1.0" +dependencies = [ + "sorted-vec", +] + +[[package]] +name = "sorted-vec" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6734caf0b6f51addd5eeacca12fb39b2c6c14e8d4f3ac42f3a78955c0467458" diff --git a/2022/day01/Cargo.toml b/2022/day01/Cargo.toml index 5a61072..76493dd 100644 --- a/2022/day01/Cargo.toml +++ b/2022/day01/Cargo.toml @@ -6,3 +6,4 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +sorted-vec = "0.8.3" diff --git a/2022/day01/src/main.rs b/2022/day01/src/main.rs index 066a4be..d6b2d2a 100644 --- a/2022/day01/src/main.rs +++ b/2022/day01/src/main.rs @@ -1,14 +1,39 @@ +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>> { 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, 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 mut max = 0; + let step = get_step(); + + let mut max: SortedVec = SortedVec::new(); let mut current = 0; for line in read_lines("input.txt")? { @@ -16,12 +41,12 @@ fn main() -> Result<(), io::Error> { current = match text.parse::() { Ok(value) => current + value, Err(_) => { - if current > max { max = current; } + update_max(&mut max, current, step); 0 }, - }; + } } - println!("{}", max); + println!("{}", max.iter().fold(0i32, |sum, i| sum + (*i as i32))); Ok(()) }