aoc/year2019/
day08.rs

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