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