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