2022: day 01 part 1

This commit is contained in:
Antoine Martin 2022-12-05 22:57:19 +01:00
parent a5fd485c10
commit f3f3b40d47
12 changed files with 2415 additions and 6 deletions

18
aoc2022/Cargo.toml Normal file
View file

@ -0,0 +1,18 @@
[package]
name = "aoc2022"
version = "0.1.0"
authors = ["Antoine Martin <antoine@alarsyo.net>"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aoc = { path = "../aoc" }
anyhow = "1.0"
[lib]
path = "src/lib.rs"
[[bin]]
name = "aoc2022"
path = "src/main.rs"

View file

@ -0,0 +1,17 @@
[package]
name = "aoc2022_bench"
version = "0.1.0"
authors = ["Antoine Martin <antoine@alarsyo.net>"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aoc2022 = { path = "../" }
[dev-dependencies]
criterion = "0.3"
[[bench]]
name = "aoc2022_bench"
harness = false

View file

@ -0,0 +1,14 @@
use criterion::{criterion_group, criterion_main, Criterion};
use aoc2022::day01;
fn aoc2022_all(c: &mut Criterion) {
c.bench_function("day01", |b| b.iter(|| day01::run().unwrap()));
}
criterion_group! {
name = all_days;
config = Criterion::default().sample_size(200);
targets = aoc2022_all
}
criterion_main!(all_days);

2253
aoc2022/input/day01.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,14 @@
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

63
aoc2022/src/day01.rs Normal file
View file

@ -0,0 +1,63 @@
use std::fmt::Write;
use anyhow::{Context, Result};
const INPUT: &str = include_str!("../input/day01.txt");
pub fn run() -> Result<String> {
let mut res = String::with_capacity(128);
writeln!(res, "part 1: {}", part1(INPUT)?)?;
Ok(res)
}
fn part1(input: &str) -> Result<u64> {
let inventories = input
.split("\n\n")
.map(str::parse::<Inventory>)
.collect::<Result<Vec<_>>>()?;
inventories
.iter()
.map(Inventory::total_calories)
.max()
.context("inventory list was empty")
}
struct Inventory(Vec<u64>);
impl std::str::FromStr for Inventory {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Inventory(
s.lines()
.map(|line| line.parse::<u64>().map_err(anyhow::Error::new))
.collect::<Result<Vec<_>>>()?,
))
}
}
impl Inventory {
fn total_calories(&self) -> u64 {
self.0.iter().sum()
}
}
#[cfg(test)]
mod tests {
use super::*;
const PROVIDED: &str = include_str!("../input/day01_provided.txt");
#[test]
fn part1_provided() {
assert_eq!(part1(PROVIDED).unwrap(), 24000);
}
#[test]
fn part1_real() {
assert_eq!(part1(INPUT).unwrap(), 68923);
}
}

3
aoc2022/src/lib.rs Normal file
View file

@ -0,0 +1,3 @@
#![warn(clippy::explicit_iter_loop, clippy::redundant_closure_for_method_calls)]
pub mod day01;

11
aoc2022/src/main.rs Normal file
View file

@ -0,0 +1,11 @@
use anyhow::Result;
use aoc::DayFunc;
use aoc2022::day01;
fn main() -> Result<()> {
let days: &[DayFunc] = &[day01::run];
aoc::run(days)
}