From 57d36aafff123f2379c7665f7be85703af75a1b1 Mon Sep 17 00:00:00 2001 From: Shivesh Mandalia Date: Tue, 20 Dec 2022 16:55:43 +0000 Subject: refactor 01a and 01b using itertools --- day01a/Cargo.toml | 1 + day01a/src/main.rs | 72 +++++++++++++++++++++++------------------------------- 2 files changed, 31 insertions(+), 42 deletions(-) (limited to 'day01a') diff --git a/day01a/Cargo.toml b/day01a/Cargo.toml index d768066..cc1c83a 100644 --- a/day01a/Cargo.toml +++ b/day01a/Cargo.toml @@ -7,3 +7,4 @@ edition = "2021" [dependencies] clap = { version = "3.2.20", features = ["derive"] } +itertools = "0.10.5" diff --git a/day01a/src/main.rs b/day01a/src/main.rs index 64b1c7e..6c6faa7 100644 --- a/day01a/src/main.rs +++ b/day01a/src/main.rs @@ -58,6 +58,7 @@ /// /// Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? use clap::Parser; +use itertools::Itertools; use std::collections::BinaryHeap; use std::fs::File; @@ -96,43 +97,39 @@ 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::().unwrap(); - - // Accumulate the calorie count for this elf - calorie_count.calories += calories; - - // Clear the line for the next iteration - line.clear(); - } + let res = reader + .lines() + .map(|l| l.unwrap()) + .peekable() + .batching(|it| { + if it.peek().is_none() { + return None; + } + // TODO(shivesh): use the std::iter try_collect method when possible + Some( + it.take_while(|l| !l.is_empty()) + .map(|w| w.parse::().unwrap()) + .collect::>(), + ) + }) + .zip(1..) + .scan(&mut heap, |heap, (batch, elf)| { + heap.push(CalorieCount { + elf, + calories: batch.into_iter().sum(), + }); + match heap.peek() { + None => None, + Some(&v) => Some(v), + } + }) + .last(); // Find the elf carrying the most calories - let res = heap.peek().unwrap(); + let res = res.unwrap(); println!( "The most amount of calories carried by an elf is {} and is carried by elf {}", res.calories, res.elf @@ -142,13 +139,4 @@ fn main() { .inspect(|x| println!("calories={:6} elf={}", x.calories, x.elf)) .take(10) .last(); - - println!( - "{}", - include_str!("../examples/input.txt") - .split("\n\n") - .map(|e| e.lines().map(|c| c.parse::().unwrap()).sum::()) - .max() - .unwrap() - ); } -- cgit v1.2.3