Compare commits

...

3 Commits

Author SHA1 Message Date
108ef47eb5 Day 1, puzzle 2 2022-12-13 13:12:04 +01:00
84ee26264b day1: Extract input parsing to lib 2022-12-12 20:05:28 +01:00
f7fe704a12 It isn't 2023 yet 2022-12-12 20:05:02 +01:00
7 changed files with 53 additions and 6 deletions

2
Cargo.lock generated
View File

@ -3,5 +3,5 @@
version = 3
[[package]]
name = "aoc23"
name = "aoc22"
version = "0.1.0"

View File

@ -1,5 +1,5 @@
[package]
name = "aoc23"
name = "aoc22"
version = "0.1.0"
edition = "2021"
@ -9,4 +9,3 @@ edition = "2021"
[[bin]]
name = "d1p1"
path = "src/d1p1.rs"

8
src/bin/d1p1.rs Normal file
View File

@ -0,0 +1,8 @@
use aoc22::day1;
fn main() {
let elves = day1::read_elves();
let max = elves.iter().max().unwrap();
println!("The elf with the most calories is carrying {} cal", max);
}

15
src/bin/d1p2.rs Normal file
View 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>()
);
}

View File

@ -1,6 +1,6 @@
use std::io;
fn main() {
pub fn read_elves() -> Vec<u32> {
println!("What's the calorie list?");
let lines = io::stdin().lines();
let mut was_empty = false;
@ -23,6 +23,5 @@ fn main() {
elves.push(prev_calories + calories);
}
let max = elves.iter().max().unwrap();
println!("The elf with the most calories is carrying {} cal", max);
elves
}

2
src/lib.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod day1;
pub mod util;

24
src/util.rs Normal file
View 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)
}