day(01): DRY
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
1d5c91536c
commit
3ced2ec0e6
1 changed files with 18 additions and 51 deletions
|
@ -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<i32> = 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<i32> {
|
||||
|
|
Loading…
Reference in a new issue