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.
11pub fn part1(input: &[u8]) -> u32 {
12    let mut most = 0;
13    let mut result = 0;
14
15    for layer in input.chunks_exact(LAYER_SIZE) {
16        let mut ones = 0;
17        let mut twos = 0;
18
19        for &b in layer {
20            ones += u32::from(b & 1);
21            twos += u32::from((b >> 1) & 1);
22        }
23
24        if ones + twos > most {
25            most = ones + twos;
26            result = ones * twos;
27        }
28    }
29
30    result
31}
32
33/// Since a black or white pixel covers those in lower layers, it's faster to check each pixel
34/// stopping as soon as we hit a non-transparent value.
35pub fn part2(input: &[u8]) -> String {
36    // Ensure enough capacity including newlines.
37    let mut result = String::with_capacity((WIDTH + 1) * HEIGHT);
38
39    for y in 0..HEIGHT {
40        result.push('\n');
41
42        for x in 0..WIDTH {
43            let mut i = WIDTH * y + x;
44
45            while input[i] == b'2' {
46                i += LAYER_SIZE;
47            }
48
49            result.push(if input[i] == b'1' { '#' } else { '.' });
50        }
51    }
52
53    result
54}