Lean in to using a heap.
This commit is contained in:
parent
cc8158e35e
commit
5dfd5512e5
1 changed files with 11 additions and 16 deletions
|
@ -1,40 +1,35 @@
|
|||
use aoc_runner_derive::{aoc as aoc_run, aoc_generator};
|
||||
use std::collections::BinaryHeap;
|
||||
|
||||
type Beep = BinaryHeap<u32>;
|
||||
|
||||
#[aoc_generator(day1)]
|
||||
fn parse_input_day1(input: &str) -> Vec<i32> {
|
||||
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::<i32>() {
|
||||
if let Ok(n) = line.parse::<u32>() {
|
||||
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()
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue