summaryrefslogtreecommitdiffstats
path: root/day01b/src
diff options
context:
space:
mode:
Diffstat (limited to 'day01b/src')
-rw-r--r--day01b/src/main.rs71
1 files changed, 30 insertions, 41 deletions
diff --git a/day01b/src/main.rs b/day01b/src/main.rs
index 4c880c4..1f93202 100644
--- a/day01b/src/main.rs
+++ b/day01b/src/main.rs
@@ -16,6 +16,7 @@
/// Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying
/// in total?
use clap::Parser;
+use itertools::Itertools;
use std::collections::BinaryHeap;
use std::fs::File;
@@ -54,53 +55,41 @@ fn main() {
let args = Cli::parse();
let file = File::open(&args.file).unwrap();
- let mut reader = BufReader::new(file);
+ let reader = BufReader::new(file);
let mut heap = BinaryHeap::new();
- let mut line = String::new();
- let mut calorie_count = CalorieCount {
- elf: 1,
- calories: 0,
- };
- while let Ok(bytes) = reader.read_line(&mut line) {
- // EOF
- if bytes == 0 {
- heap.push(calorie_count);
- break;
- }
-
- // Newlines
- let tline = line.trim();
- if tline.is_empty() {
- // Push onto the binary heap
- heap.push(calorie_count);
- calorie_count.calories = 0;
- calorie_count.elf += 1;
- continue;
- }
-
- // Parse the calories
- let calories = tline.parse::<usize>().unwrap();
-
- // Accumulate the calorie count for this elf
- calorie_count.calories += calories;
-
- // Clear the line for the next iteration
- line.clear();
- }
-
- // Find the elf carrying the most calories
+ let _ = reader
+ .lines()
+ .map(|l| l.unwrap())
+ .peekable()
+ .batching(|it| {
+ if it.peek().is_none() {
+ return None;
+ }
+ Some(
+ it.take_while(|l| !l.is_empty())
+ .map(|w| w.parse::<usize>().unwrap())
+ .collect::<Vec<usize>>(),
+ )
+ })
+ .zip(1..)
+ .scan(&mut heap, |heap, (batch, elf)| {
+ heap.push(CalorieCount {
+ elf,
+ calories: batch.iter().sum(),
+ });
+ match heap.peek() {
+ None => None,
+ Some(_) => Some(()),
+ }
+ })
+ .last();
+
+ // Find the top 3 elves carrying the most calories
let res = heap
.into_iter_sorted()
.inspect(|x| println!("calories={:6} elf={}", x.calories, x.elf))
.take(3)
.fold(0usize, |acc, x| acc + x.calories);
println!("The top 3 elves are carry {res} calories");
-
- let mut cals = include_str!("../examples/input.txt")
- .split("\n\n")
- .map(|e| e.lines().map(|c| c.parse::<u32>().unwrap()).sum())
- .collect::<Vec<u32>>();
- cals.sort_unstable();
- println!("{}", cals.into_iter().rev().take(3).sum::<u32>());
}