Files
aoc2022/src/day1.rs

61 lines
1.0 KiB
Rust

use aoc_runner_derive::{aoc, aoc_generator};
use itertools::Itertools;
use std::io::BufRead;
#[aoc_generator(day1)]
// Sum the calories of each elf's food items
fn parse(input: &[u8]) -> Vec<u64> {
let mut result = Vec::new();
let mut cur_elf = 0u64;
for line in input.lines() {
if let Ok(calories) = line.unwrap().parse::<u64>() {
cur_elf += calories
} else {
result.push(cur_elf);
cur_elf = 0
}
}
result.push(cur_elf);
result
}
#[aoc(day1, part1)]
fn part1(input: &Vec<u64>) -> u64 {
*input.iter().max().unwrap()
}
#[aoc(day1, part2)]
fn part2(input: &Vec<u64>) -> u64 {
input.iter().sorted().rev().take(3).sum::<u64>()
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE: &[u8] = b"1000
2000
3000
4000
5000
6000
7000
8000
9000
10000";
#[test]
fn part1_example() {
assert_eq!(part1(&parse(EXAMPLE)), 24000);
}
#[test]
fn part2_example() {
assert_eq!(part2(&parse(EXAMPLE)), 45000);
}
}