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::iter::repeat_with;
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<Vec<Item<'_>>> = repeat_with(Vec::new).take(256).collect();
18
19    for step in input.trim().as_bytes().split(|&b| b == b',') {
20        let size = step.len();
21        part_one += hash(step);
22
23        if step[size - 1] == b'-' {
24            let label = &step[..size - 1];
25            let hash = hash(label);
26            let slot = &mut boxes[hash];
27
28            // If the label exists then remove it.
29            if let Some(i) = slot.iter().position(|item| item.label == label) {
30                slot.remove(i);
31            }
32        } else {
33            let label = &step[..size - 2];
34            let hash = hash(label);
35            let slot = &mut boxes[hash];
36            let lens = step[size - 1].to_decimal() as usize;
37
38            // Replace or append new lens.
39            if let Some(i) = slot.iter().position(|item| item.label == label) {
40                slot[i].lens = lens;
41            } else {
42                slot.push(Item { label, lens });
43            }
44        }
45    }
46
47    for (i, next) in boxes.iter().enumerate() {
48        for (j, item) in next.iter().enumerate() {
49            part_two += (i + 1) * (j + 1) * item.lens;
50        }
51    }
52
53    (part_one, part_two)
54}
55
56pub fn part1(input: &Input) -> usize {
57    input.0
58}
59
60pub fn part2(input: &Input) -> usize {
61    input.1
62}
63
64/// Custom hash function.
65#[inline]
66fn hash(slice: &[u8]) -> usize {
67    slice.iter().fold(0, |acc, &b| ((acc + b as usize) * 17) & 0xff)
68}