-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathd15.rs
More file actions
77 lines (64 loc) · 2.12 KB
/
d15.rs
File metadata and controls
77 lines (64 loc) · 2.12 KB
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
use crate::Day;
pub struct Day15 {}
impl Day for Day15 {
fn year(&self) -> u16 {
2023
}
fn day(&self) -> u8 {
15
}
fn part_one(&self) -> String {
self.read_default_input()
.lines()
.next()
.unwrap()
.split(',')
.map(hash)
.sum::<u32>()
.to_string()
}
fn part_two(&self) -> String {
let mut boxes: Vec<Vec<(String, u8)>> = vec![Vec::new(); 256];
self.read_default_input()
.lines()
.next()
.unwrap()
.split(',')
.for_each(|item| {
if item.contains('-') {
let tokens = item.split('-').collect::<Vec<_>>();
let label = tokens[0];
let box_index = hash(label) as usize;
boxes[box_index].retain(|lens| lens.0 != label);
} else if item.contains('=') {
let tokens = item.split('=').collect::<Vec<_>>();
let label = tokens[0];
let box_index = hash(label) as usize;
let focal_length = tokens[1].parse::<u8>().unwrap();
match boxes[box_index].iter_mut().find(|lens| lens.0 == label) {
Some(lens) => lens.1 = focal_length,
None => boxes[box_index].push((label.to_string(), focal_length)),
}
} else {
unreachable!()
};
});
let mut lenses_focus_power = 0;
for (box_index, r#box) in boxes.iter().enumerate() {
for (slot_index, lens) in r#box.iter().enumerate() {
lenses_focus_power += (box_index + 1) * (slot_index + 1) * lens.1 as usize;
}
}
lenses_focus_power.to_string()
}
}
fn hash(input: &str) -> u32 {
let chars = input.chars().map(|c| c as u32).collect::<Vec<u32>>();
let mut current_value = 0;
for c in chars {
current_value += c;
current_value *= 17;
current_value %= 256;
}
current_value
}