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. Assumes labels are always
4//! 8 characters or fewer.
5use crate::util::parse::*;
6
7type Input = (usize, usize);
8
9struct Item {
10    label: usize,
11    lens: usize,
12}
13
14pub fn parse(input: &str) -> Input {
15    let input = input.trim().as_bytes();
16
17    let mut part_one = 0;
18    let mut part_two = 0;
19    let mut hash = 0;
20    let mut label = 0;
21    let mut boxes: [Vec<Item>; 256] = [const { Vec::new() }; 256];
22
23    for (i, &b) in input.iter().enumerate() {
24        match b {
25            b',' => {
26                part_one += hash;
27                hash = 0;
28                label = 0;
29                continue;
30            }
31            b'-' => boxes[hash].retain(|item| item.label != label),
32            b'=' => {
33                let lens = input[i + 1].to_decimal();
34                let slot = &mut boxes[hash];
35
36                match slot.iter_mut().find(|item| item.label == label) {
37                    Some(item) => item.lens = lens,
38                    None => slot.push(Item { label, lens }),
39                }
40            }
41            _ => (),
42        }
43
44        let u = usize::from(b);
45        hash = ((hash + u) * 17) & 0xff;
46        label = (label << 8) | u;
47    }
48
49    for (i, next) in boxes.iter().enumerate() {
50        for (j, item) in next.iter().enumerate() {
51            part_two += (i + 1) * (j + 1) * item.lens;
52        }
53    }
54
55    // The final step has no trailing comma.
56    (part_one + hash, part_two)
57}
58
59pub fn part1(input: &Input) -> usize {
60    input.0
61}
62
63pub fn part2(input: &Input) -> usize {
64    input.1
65}