From 3e9c1ee1c1900e3a67023bd1f977883810c01dda Mon Sep 17 00:00:00 2001 From: Xiretza Date: Mon, 18 Dec 2023 17:42:48 +0000 Subject: [PATCH] 2023 day15/rust: add solution --- 2023/day15/rust/Cargo.toml | 9 ++++++ 2023/day15/rust/src/main.rs | 56 +++++++++++++++++++++++++++++++++++++ Cargo.lock | 7 +++++ Cargo.toml | 1 + 4 files changed, 73 insertions(+) create mode 100644 2023/day15/rust/Cargo.toml create mode 100644 2023/day15/rust/src/main.rs diff --git a/2023/day15/rust/Cargo.toml b/2023/day15/rust/Cargo.toml new file mode 100644 index 0000000..0f2e233 --- /dev/null +++ b/2023/day15/rust/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "rust_2023_15" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +aoc = { path = "../../../common/rust" } diff --git a/2023/day15/rust/src/main.rs b/2023/day15/rust/src/main.rs new file mode 100644 index 0000000..3ae61b3 --- /dev/null +++ b/2023/day15/rust/src/main.rs @@ -0,0 +1,56 @@ +#![warn(clippy::pedantic)] + +use std::io::{stdin, Read}; + +fn hash(s: &str) -> u8 { + s.as_bytes() + .iter() + .copied() + .fold(0, |acc, b| acc.wrapping_add(b).wrapping_mul(17)) +} + +fn main() { + let mut input = String::new(); + stdin().read_to_string(&mut input).unwrap(); + let input = input.trim(); + + let steps = input.split(','); + + println!( + "{}", + steps.clone().map(|s| { u64::from(hash(s)) }).sum::() + ); + + let mut boxes: [Vec<(&str, usize)>; 256] = std::array::from_fn(|_| Vec::new()); + + for step in steps { + let (label, focal_length) = if let Some(label) = step.strip_suffix('-') { + (label, None) + } else { + let (label, focal_length) = step.split_once('=').unwrap(); + (label, Some(focal_length.parse().unwrap())) + }; + + let b = &mut boxes[usize::from(hash(label))]; + if let Some(existing_pos) = b.iter().position(|&(l, _fl)| l == label) { + if let Some(fl) = focal_length { + b[existing_pos].1 = fl; + } else { + b.remove(existing_pos); + } + } else if let Some(fl) = focal_length { + b.push((label, fl)); + } + } + + let focal_powers = boxes.into_iter().enumerate().flat_map(|(box_num, lenses)| { + lenses + .into_iter() + .enumerate() + .map(move |(lens_num, (_label, focal_length))| { + (box_num + 1) * (lens_num + 1) * focal_length + }) + }); + + println!("{}", focal_powers.sum::()); +} diff --git a/Cargo.lock b/Cargo.lock index a472174..eff8c27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -695,6 +695,13 @@ dependencies = [ "itertools 0.12.0", ] +[[package]] +name = "rust_2023_15" +version = "0.1.0" +dependencies = [ + "aoc", +] + [[package]] name = "rustversion" version = "1.0.14" diff --git a/Cargo.toml b/Cargo.toml index 7136998..1a01457 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,4 +36,5 @@ members = [ "2023/day8/rust", "2023/day9/rust", "2023/day11/rust", + "2023/day15/rust", ]