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::*;
|
||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
use std::cmp::max;
|
fn n_biggest(n: usize, input: &[i32]) -> i32 {
|
||||||
|
|
||||||
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 {
|
|
||||||
let mut calories: Vec<i32> = Vec::new();
|
let mut calories: Vec<i32> = Vec::new();
|
||||||
|
|
||||||
let last_elf = input
|
let last_elf = input.iter().fold(0, |a, &x| {
|
||||||
.iter()
|
if x == -1 {
|
||||||
.fold(Accum::new(), |a, &x| {
|
calories.push(a);
|
||||||
if x == -1 {
|
0
|
||||||
calories.push(a.current_sum);
|
} else {
|
||||||
Accum::new()
|
a + x
|
||||||
} else {
|
}
|
||||||
Accum {
|
});
|
||||||
max_sum: a.max_sum,
|
|
||||||
current_sum: a.current_sum + x,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.current_sum;
|
|
||||||
calories.push(last_elf);
|
calories.push(last_elf);
|
||||||
|
|
||||||
calories.sort();
|
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> {
|
fn parse_input(pathname: &str) -> Vec<i32> {
|
||||||
|
|
Loading…
Reference in a new issue