1use crate::util::iter::*;
10use crate::util::parse::*;
11
12const SIZE: usize = 24;
13
14pub fn parse(input: &str) -> Vec<u8> {
15 let mut cube = vec![0; SIZE * SIZE * SIZE];
16 input.iter_unsigned().chunk::<3>().for_each(|[x, y, z]: [usize; 3]| {
19 cube[(x + 1) * SIZE * SIZE + (y + 1) * SIZE + (z + 1)] = 1;
20 });
21 cube
22}
23
24pub fn part1(input: &[u8]) -> u32 {
25 count(input, |x| 6 - x)
27}
28
29pub fn part2(input: &[u8]) -> u32 {
30 let mut cube = input.to_vec();
33 cube[0] = 8;
34
35 let mut todo = Vec::new();
36 todo.push(0);
37
38 while let Some(index) = todo.pop() {
39 let mut flood_fill = |next| {
40 if next < input.len() && cube[next] == 0 {
41 cube[next] = 8;
42 todo.push(next);
43 }
44 };
45
46 flood_fill(index.wrapping_sub(1));
48 flood_fill(index + 1);
49 flood_fill(index.wrapping_sub(SIZE));
50 flood_fill(index + SIZE);
51 flood_fill(index.wrapping_sub(SIZE * SIZE));
52 flood_fill(index + SIZE * SIZE);
53 }
54
55 count(&cube, |x| x >> 3)
57}
58
59fn count(cube: &[u8], adjust: fn(u32) -> u32) -> u32 {
60 let mut total = 0;
61
62 for (i, &cell) in cube.iter().enumerate() {
63 if cell == 1 {
64 let neighbors = cube[i - 1] as u32
66 + cube[i + 1] as u32
67 + cube[i - SIZE] as u32
68 + cube[i + SIZE] as u32
69 + cube[i - SIZE * SIZE] as u32
70 + cube[i + SIZE * SIZE] as u32;
71 total += adjust(neighbors);
72 }
73 }
74
75 total
76}