aoc/year2019/
day08.rs

1//! # Space Image Format
2
3pub fn parse(input: &str) -> &str {
4    input
5}
6
7/// Each layer is 25 * 6 = 150 bytes and there are 100 layers total.
8/// It's faster to count pixels 8 at a time by parsing the bytes as `u64` then using bitwise logic
9/// and the [`count_ones`] intrinsic. The only minor wrinkle is that 8 does not divide 150 evenly
10/// so we must handle the last 6 bytes specially.
11///
12/// [`count_ones`]: u64::count_ones
13pub fn part1(input: &str) -> u32 {
14    let bytes = input.as_bytes();
15    let mut index = 0;
16    let mut ones = 0;
17    let mut twos = 0;
18    let mut most = 0;
19    let mut result = 0;
20
21    for _ in 0..100 {
22        // First 144 of 150 bytes.
23        for _ in 0..18 {
24            let slice = &bytes[index..(index + 8)];
25            let n = u64::from_be_bytes(slice.try_into().unwrap());
26            ones += (n & 0x0101010101010101).count_ones();
27            twos += (n & 0x0202020202020202).count_ones();
28            index += 8;
29        }
30
31        // Handle remaining 6 bytes.
32        // The masks exclude the most significant 2 bytes to prevent double counting.
33        let slice = &bytes[(index - 2)..(index + 6)];
34        let n = u64::from_be_bytes(slice.try_into().unwrap());
35        ones += (n & 0x0000010101010101).count_ones();
36        twos += (n & 0x0000020202020202).count_ones();
37        index += 6;
38
39        if ones + twos > most {
40            most = ones + twos;
41            result = ones * twos;
42        }
43
44        ones = 0;
45        twos = 0;
46    }
47
48    result
49}
50
51/// Since a black or white pixel covers those in lower layers, it's faster to check each pixel
52/// stopping as soon as we hit a non-transparent value.
53pub fn part2(input: &str) -> String {
54    let bytes = input.as_bytes();
55    let mut image = ['.'; 150];
56
57    for (i, pixel) in image.iter_mut().enumerate() {
58        let mut j = i;
59
60        while bytes[j] == b'2' {
61            j += 150;
62        }
63
64        if bytes[j] == b'1' {
65            *pixel = '#';
66        }
67    }
68
69    let mut result =
70        image.chunks_exact(25).map(|row| row.iter().collect()).collect::<Vec<String>>().join("\n");
71    result.insert(0, '\n');
72    result
73}