diff --git a/src/bin/day01.rs b/src/bin/day01.rs index fba0699..2219da9 100644 --- a/src/bin/day01.rs +++ b/src/bin/day01.rs @@ -3,62 +3,29 @@ use aoc_2022::file_to_lines; use tracing::*; use tracing_subscriber::EnvFilter; -use std::cmp::max; - -struct Accum { - max_sum: i32, - current_sum: i32, -} - -impl Accum { - fn new() -> Accum { - Accum { - max_sum: 0, - current_sum: 0, - } - } -} - -fn part_1(input: &[i32]) -> i32 { - input - .iter() - .fold(Accum::new(), |a, &x| { - if x == -1 { - Accum { - max_sum: max(a.max_sum, a.current_sum), - current_sum: 0, - } - } else { - Accum { - max_sum: a.max_sum, - current_sum: a.current_sum + x, - } - } - }) - .max_sum -} - -fn part_2(input: &[i32]) -> i32 { +fn n_biggest(n: usize, input: &[i32]) -> i32 { let mut calories: Vec = Vec::new(); - let last_elf = input - .iter() - .fold(Accum::new(), |a, &x| { - if x == -1 { - calories.push(a.current_sum); - Accum::new() - } else { - Accum { - max_sum: a.max_sum, - current_sum: a.current_sum + x, - } - } - }) - .current_sum; + let last_elf = input.iter().fold(0, |a, &x| { + if x == -1 { + calories.push(a); + 0 + } else { + a + x + } + }); calories.push(last_elf); calories.sort(); - calories.iter().rev().take(3).sum() + calories.iter().rev().take(n).sum() +} + +fn part_1(input: &[i32]) -> i32 { + n_biggest(1_usize, input) +} + +fn part_2(input: &[i32]) -> i32 { + n_biggest(3_usize, input) } fn parse_input(pathname: &str) -> Vec {