generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.rs
96 lines (84 loc) · 2.44 KB
/
15.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use itertools::Itertools;
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::{alpha1, digit1};
use nom::combinator::{map, map_res};
use nom::sequence::{preceded, tuple};
use nom::IResult;
advent_of_code::solution!(15);
fn hash(s: &str) -> u8 {
s.chars().fold(0, |acc, c| {
if c.is_ascii_whitespace() {
acc
} else {
acc.wrapping_add(c as u8).wrapping_mul(17)
}
})
}
pub fn part_one(input: &str) -> Option<u32> {
input.split(',').map(|s| hash(s) as u32).sum1()
}
enum Operation {
Remove,
Insert(u32),
}
fn parse_step(s: &str) -> IResult<&str, (&str, Operation)> {
tuple((
alpha1,
alt((
map(tag("-"), |_| Operation::Remove),
map(
preceded(tag("="), map_res(digit1, str::parse)),
Operation::Insert,
),
)),
))(s)
}
pub fn part_two(input: &str) -> Option<u32> {
let mut hash_map: Vec<Vec<(&str, u32)>> = vec![vec![]; 256];
input
.split(',')
.map(|s| parse_step(s).unwrap().1)
.for_each(|(label, operation)| {
let index = hash_map[hash(label) as usize]
.iter()
.position(|entry| entry.0 == label);
match (operation, index) {
(Operation::Remove, Some(index)) => {
hash_map[hash(label) as usize].remove(index);
}
(Operation::Insert(value), None) => {
hash_map[hash(label) as usize].push((label, value));
}
(Operation::Insert(value), Some(index)) => {
hash_map[hash(label) as usize][index].1 = value;
}
_ => {}
}
});
hash_map
.iter()
.enumerate()
.map(|(box_idx, slots)| {
slots
.iter()
.enumerate()
.map(|(slot_idx, (_, value))| (box_idx + 1) as u32 * (slot_idx + 1) as u32 * value)
.sum::<u32>()
})
.sum1()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(1320));
}
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(145));
}
}