-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.rs
122 lines (98 loc) · 2.7 KB
/
day14.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
//! [Day 14: Disk Defragmentation](https://adventofcode.com/2017/day/14)
use aoc::grid::Grid;
use aoc::knot;
const fn count_ones(value: u8) -> u32 {
let mut count = 0;
let mut value = value;
while value != 0 {
count += 1;
value &= value - 1;
}
count
}
struct Puzzle {
key: String,
}
impl Puzzle {
const fn new() -> Self {
Self { key: String::new() }
}
/// Get the puzzle input.
fn configure(&mut self, path: &str) {
let data = std::fs::read_to_string(path).unwrap();
self.key = data.trim().to_string();
}
/// Solve part one.
fn part1(&self) -> u32 {
(0..128)
.map(|i| {
knot::hash_raw(format!("{}-{i}", self.key).as_str())
.iter()
.copied()
.map(count_ones)
.sum::<u32>()
})
.sum()
}
/// Solve part two.
fn part2(&self) -> u32 {
let mut g: Grid<u8> = Grid::with_size(128, 128);
for y in 0..128 {
let row = knot::hash_raw(format!("{}-{y}", self.key).as_str());
for (i, octet) in row.iter().enumerate() {
//
for b in 0..8 {
let x = (i * 8) + b;
let o = (octet >> (7 - b)) & 1;
g[(x, y)] = o;
}
}
}
let mut q = vec![];
let mut result = 0;
for y in 0..128 {
for x in 0..128 {
if g[(x, y)] == 0 {
continue;
}
result += 1;
// bfs to find all adjacent used squares
q.push((x, y));
while let Some((x, y)) = q.pop() {
g[(x, y)] = 0; // cancel the square so we don't need to maintain a 'visited' set
for (nx, ny) in g.iter_directions((x, y)) {
if g[(nx, ny)] == 1 {
q.push((nx, ny));
}
}
}
}
//
}
result
}
}
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(args.path.as_str());
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test01() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part1(), 8108);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
puzzle.configure("test.txt");
assert_eq!(puzzle.part2(), 1242);
}
}