Skip to main content

aoc/year2023/
day15.rs

1//! # Lens Library
2//!
3//! Calculates part one and two at the same time as a speed optimization.
4use crate::util::parse::*;
5use std::array::from_fn;
6
7type Input = (usize, usize);
8
9struct Item<'a> {
10    label: &'a [u8],
11    lens: usize,
12}
13
14pub fn parse(input: &str) -> Input {
15    let mut part_one = 0;
16    let mut part_two = 0;
17    let mut boxes: [Vec<Item<'_>>; 256] = from_fn(|_| Vec::new());
18
19    for step in input.trim().as_bytes().split(|&b| b == b',') {
20        part_one += hash(step);
21        let (&last, rest) = step.split_last().unwrap();
22
23        if last == b'-' {
24            // If the label exists then remove it.
25            boxes[hash(rest)].retain(|item| item.label != rest);
26        } else {
27            let label = &rest[..rest.len() - 1];
28            let slot = &mut boxes[hash(label)];
29            let lens = last.to_decimal() as usize;
30
31            // Replace or append new lens.
32            if let Some(i) = slot.iter().position(|item| item.label == label) {
33                slot[i].lens = lens;
34            } else {
35                slot.push(Item { label, lens });
36            }
37        }
38    }
39
40    for (i, next) in boxes.iter().enumerate() {
41        for (j, item) in next.iter().enumerate() {
42            part_two += (i + 1) * (j + 1) * item.lens;
43        }
44    }
45
46    (part_one, part_two)
47}
48
49pub fn part1(input: &Input) -> usize {
50    input.0
51}
52
53pub fn part2(input: &Input) -> usize {
54    input.1
55}
56
57/// Custom hash function.
58#[inline]
59fn hash(slice: &[u8]) -> usize {
60    slice.iter().fold(0, |acc, &b| ((acc + b as usize) * 17) & 0xff)
61}