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 let size = step.len();
21 part_one += hash(step);
22
23 if step[size - 1] == b'-' {
24 let label = &step[..size - 1];
25 boxes[hash(label)].retain(|item| item.label != label);
27 } else {
28 let label = &step[..size - 2];
29 let hash = hash(label);
30 let slot = &mut boxes[hash];
31 let lens = step[size - 1].to_decimal() as usize;
32
33 if let Some(i) = slot.iter().position(|item| item.label == label) {
35 slot[i].lens = lens;
36 } else {
37 slot.push(Item { label, lens });
38 }
39 }
40 }
41
42 for (i, next) in boxes.iter().enumerate() {
43 for (j, item) in next.iter().enumerate() {
44 part_two += (i + 1) * (j + 1) * item.lens;
45 }
46 }
47
48 (part_one, part_two)
49}
50
51pub fn part1(input: &Input) -> usize {
52 input.0
53}
54
55pub fn part2(input: &Input) -> usize {
56 input.1
57}
58
59#[inline]
61fn hash(slice: &[u8]) -> usize {
62 slice.iter().fold(0, |acc, &b| ((acc + b as usize) * 17) & 0xff)
63}