From 5dfd5512e5d6f06896cc85ec691fad6d0567b1e9 Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Thu, 1 Dec 2022 13:01:06 -0800 Subject: [PATCH] Lean in to using a heap. --- 2022-aoc/src/d1.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/2022-aoc/src/d1.rs b/2022-aoc/src/d1.rs index ce14b48..9226ee6 100644 --- a/2022-aoc/src/d1.rs +++ b/2022-aoc/src/d1.rs @@ -1,40 +1,35 @@ use aoc_runner_derive::{aoc as aoc_run, aoc_generator}; +use std::collections::BinaryHeap; + +type Beep = BinaryHeap; #[aoc_generator(day1)] -fn parse_input_day1(input: &str) -> Vec { +fn parse_input_day1(input: &str) -> Beep { let mut cur = 0; - let mut out = Vec::new(); + let mut out = BinaryHeap::new(); for line in input.lines() { - if let Ok(n) = line.parse::() { + if let Ok(n) = line.parse::() { cur += n; } else { out.push(cur); cur = 0; } } - out } #[aoc_run(day1, part1)] -fn part1(calories: &[i32]) -> i32 { - unsafe { *calories.iter().max().unwrap_unchecked() } +fn part1(cals: &Beep) -> u32 { + let mut cals = cals.to_owned(); + cals.pop().unwrap() } #[aoc_run(day1, part2)] -fn p2(cals: &[i32]) -> i32 { - let mut cals = std::collections::BinaryHeap::from_iter(cals.iter().copied()); +fn p2(cals: &Beep) -> u32 { + let mut cals = cals.to_owned(); let mut out = 0; for _ in 0..3 { out += cals.pop().unwrap(); } out } - -// much slower than using a heap -#[aoc_run(day1, part2, alt)] -fn p2a(cals: &[i32]) -> i32 { - let mut cals = cals.to_owned(); - cals.sort_unstable_by(|x, y| y.cmp(x)); - cals.iter().take(3).sum() -}