1use 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 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 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#[inline]
59fn hash(slice: &[u8]) -> usize {
60 slice.iter().fold(0, |acc, &b| ((acc + b as usize) * 17) & 0xff)
61}