Compare commits

...

2 commits

Author SHA1 Message Date
3e9c1ee1c1 2023 day15/rust: add solution 2023-12-18 17:42:48 +00:00
acea94bea5 2023 day15: add data 2023-12-18 17:42:40 +00:00
6 changed files with 76 additions and 0 deletions

2
2023/data/day15.expected Normal file
View file

@ -0,0 +1,2 @@
515210
246762

1
2023/data/day15.input Normal file

File diff suppressed because one or more lines are too long

View file

@ -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" }

View file

@ -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::<u64>()
);
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::<usize>());
}

7
Cargo.lock generated
View file

@ -695,6 +695,13 @@ dependencies = [
"itertools 0.12.0", "itertools 0.12.0",
] ]
[[package]]
name = "rust_2023_15"
version = "0.1.0"
dependencies = [
"aoc",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.14" version = "1.0.14"

View file

@ -36,4 +36,5 @@ members = [
"2023/day8/rust", "2023/day8/rust",
"2023/day9/rust", "2023/day9/rust",
"2023/day11/rust", "2023/day11/rust",
"2023/day15/rust",
] ]