2022-12-01 11:05:34 +01:00
|
|
|
use aoc_2022::file_to_lines;
|
|
|
|
|
2022-12-01 14:29:48 +01:00
|
|
|
use color_eyre::eyre::Result;
|
2022-12-01 11:05:34 +01:00
|
|
|
use tracing::*;
|
|
|
|
use tracing_subscriber::EnvFilter;
|
|
|
|
|
2022-12-01 11:30:32 +01:00
|
|
|
fn n_biggest(n: usize, input: &[i32]) -> i32 {
|
|
|
|
let mut calories: Vec<i32> = Vec::new();
|
2022-12-01 11:05:34 +01:00
|
|
|
|
2022-12-01 11:30:32 +01:00
|
|
|
let last_elf = input.iter().fold(0, |a, &x| {
|
|
|
|
if x == -1 {
|
|
|
|
calories.push(a);
|
|
|
|
0
|
|
|
|
} else {
|
|
|
|
a + x
|
2022-12-01 11:05:34 +01:00
|
|
|
}
|
2022-12-01 11:30:32 +01:00
|
|
|
});
|
|
|
|
calories.push(last_elf);
|
|
|
|
|
|
|
|
calories.sort();
|
|
|
|
calories.iter().rev().take(n).sum()
|
2022-12-01 11:05:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn part_1(input: &[i32]) -> i32 {
|
2022-12-01 11:30:32 +01:00
|
|
|
n_biggest(1_usize, input)
|
2022-12-01 11:05:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn part_2(input: &[i32]) -> i32 {
|
2022-12-01 11:30:32 +01:00
|
|
|
n_biggest(3_usize, input)
|
2022-12-01 11:05:34 +01:00
|
|
|
}
|
|
|
|
|
2022-12-01 11:23:15 +01:00
|
|
|
fn parse_input(pathname: &str) -> Vec<i32> {
|
|
|
|
file_to_lines(pathname)
|
|
|
|
.iter()
|
|
|
|
.map(|s| if s.is_empty() { -1 } else { s.parse().unwrap() })
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
2022-12-01 14:29:48 +01:00
|
|
|
fn main() -> Result<()> {
|
2022-12-01 11:05:34 +01:00
|
|
|
tracing_subscriber::fmt()
|
|
|
|
.with_env_filter(EnvFilter::from_default_env())
|
|
|
|
.with_target(false)
|
|
|
|
.with_file(true)
|
|
|
|
.with_line_number(true)
|
|
|
|
.without_time()
|
|
|
|
.compact()
|
|
|
|
.init();
|
2022-12-01 14:29:48 +01:00
|
|
|
color_eyre::install()?;
|
2022-12-01 11:05:34 +01:00
|
|
|
|
2022-12-01 11:23:15 +01:00
|
|
|
let input = parse_input("inputs/day01.txt");
|
2022-12-01 11:05:34 +01:00
|
|
|
|
|
|
|
info!("Part 1: {}", part_1(&input));
|
|
|
|
info!("Part 2: {}", part_2(&input));
|
2022-12-01 14:29:48 +01:00
|
|
|
|
|
|
|
Ok(())
|
2022-12-01 11:05:34 +01:00
|
|
|
}
|
2022-12-01 11:24:03 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_part_1() {
|
|
|
|
let sample = parse_input("samples/day01.txt");
|
|
|
|
assert_eq!(part_1(&sample), 24000);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_part_2() {
|
|
|
|
let sample = parse_input("samples/day01.txt");
|
|
|
|
assert_eq!(part_2(&sample), 45000);
|
|
|
|
}
|
|
|
|
}
|