Skip to main content

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