Day 1, puzzle 2
This commit is contained in:
15
src/bin/d1p2.rs
Normal file
15
src/bin/d1p2.rs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
use aoc22::day1;
|
||||||
|
use aoc22::util;
|
||||||
|
|
||||||
|
const N_ELVES: usize = 3;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let elves = day1::read_elves();
|
||||||
|
|
||||||
|
let max_vals = util::max_n(elves.as_slice(), N_ELVES).unwrap();
|
||||||
|
println!(
|
||||||
|
"The {} elves with the most calories are carrying {} cal",
|
||||||
|
N_ELVES,
|
||||||
|
max_vals.iter().sum::<u32>()
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -1 +1,2 @@
|
|||||||
pub mod day1;
|
pub mod day1;
|
||||||
|
pub mod util;
|
||||||
|
|||||||
24
src/util.rs
Normal file
24
src/util.rs
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
pub fn max_n<T: Ord + Copy>(slice: &[T], n: usize) -> Result<Vec<T>, ()> {
|
||||||
|
if n == 0 || n > slice.len() {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let mut max_vals = Vec::new();
|
||||||
|
for _ in 0..n {
|
||||||
|
max_vals.push(slice[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for val in slice {
|
||||||
|
if val > &max_vals[0] {
|
||||||
|
max_vals[2] = max_vals[1];
|
||||||
|
max_vals[1] = max_vals[0];
|
||||||
|
max_vals[0] = *val;
|
||||||
|
} else if val > &max_vals[1] {
|
||||||
|
max_vals[2] = max_vals[1];
|
||||||
|
max_vals[1] = *val;
|
||||||
|
} else if val > &max_vals[2] {
|
||||||
|
max_vals[2] = *val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(max_vals)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user