Skip to main content

aoc/year2017/
day14.rs

1//! # Disk Defragmentation
2//!
3//! This problem is a blend of the hashing from [`Day 10`] and the connected clique finding
4//! from [`Day 12`] and reuses the same flood fill approach to count groups.
5//!
6//! [`Day 10`]: crate::year2017::day10
7//! [`Day 12`]: crate::year2017::day12
8use std::array::from_fn;
9
10use crate::util::thread::*;
11
12/// Parallelize the hashing as each row is independent. Each worker thread chooses the next
13/// available row then computes the hash, and the final vec is patched with the results.
14pub fn parse(input: &str) -> Vec<u8> {
15    let prefix = input.trim();
16    let rows: Vec<_> = (0..128).collect();
17    let result = spawn_parallel_iterator(&rows, |iter| {
18        iter.map(|&index| (index, fill_row(prefix, index))).collect::<Vec<_>>()
19    });
20
21    let mut grid = vec![[[0; 8]; 16]; 128];
22    for (index, row) in result.into_iter().flatten() {
23        grid[index] = row;
24    }
25    grid.into_flattened().into_flattened()
26}
27
28pub fn part1(input: &[u8]) -> u32 {
29    input.iter().map(|&n| u32::from(n)).sum()
30}
31
32pub fn part2(input: &[u8]) -> usize {
33    let mut grid = input.to_vec();
34    let connect = |i| (grid[i] == 1).then(|| dfs(&mut grid, i));
35    (0..input.len()).filter_map(connect).count()
36}
37
38/// Compute the knot hash for a row and expand into a fixed-size array.
39fn fill_row(prefix: &str, index: usize) -> [[u8; 8]; 16] {
40    let s = format!("{prefix}-{index}");
41    let lengths: Vec<_> = s.bytes().map(usize::from).chain([17, 31, 73, 47, 23]).collect();
42
43    let knot = knot_hash(&lengths);
44    let mut result = [[0; 8]; 16];
45
46    for (i, chunk) in knot.chunks_exact(16).enumerate() {
47        let reduced = chunk.iter().fold(0, |acc, n| acc ^ n);
48        result[i] = from_fn(|j| (reduced >> (7 - j)) & 1);
49    }
50
51    result
52}
53
54/// Slightly tweaked version of the code from Day 10 that always performs 64 rounds.
55/// Uses a fixed-size array for better performance.
56#[inline]
57fn knot_hash(lengths: &[usize]) -> [u8; 256] {
58    let mut knot: [_; 256] = from_fn(|i| i as u8);
59    let mut position = 0;
60    let mut skip = 0;
61
62    for _ in 0..64 {
63        for &length in lengths {
64            let next = length + skip;
65            knot[0..length].reverse();
66            knot.rotate_left(next % 256);
67            position += next;
68            skip += 1;
69        }
70    }
71
72    // Rotate the array the other direction so that the original starting position is restored.
73    knot.rotate_right(position % 256);
74    knot
75}
76
77/// Flood fill that explores the connected squares in the grid.
78fn dfs(grid: &mut [u8], index: usize) {
79    grid[index] = 0;
80    let x = index % 128;
81    let y = index / 128;
82
83    if x > 0 && grid[index - 1] == 1 {
84        dfs(grid, index - 1);
85    }
86    if x < 127 && grid[index + 1] == 1 {
87        dfs(grid, index + 1);
88    }
89    if y > 0 && grid[index - 128] == 1 {
90        dfs(grid, index - 128);
91    }
92    if y < 127 && grid[index + 128] == 1 {
93        dfs(grid, index + 128);
94    }
95}