Advent of Code 2019 - Day 8

Advent of CodeRust

The problem of today was about decoding pixels for an "image".

The first part was to determine which of the layers of the image contained the most zeroes and the second part was to print out the image data to get the password.

Code

fn get_digits(input: &str) -> Vec<i32> {
    input
        .trim()
        .chars()
        .map(|c| c.to_digit(10).unwrap() as i32)
        .collect()
}

fn output_image(image: &[&str], width: i32, height: i32) {
    for i in 0..(width * height) {
        print!("{}", image[i as usize]);

        if (i + 1) % width == 0 {
            print!("\n");
        }
    }
}

pub fn part_one(input: &str, width: i32, height: i32) -> i32 {
    let digits = get_digits(input);
    let mut layers: Vec<&[i32]> = digits.chunks((width * height) as usize).collect();
    layers.sort_by_key(|x| x.iter().filter(|x| **x == 0).count());
    let layer = layers[0];
    let ones = layer.iter().filter(|x| **x == 1).count();
    let twos = layer.iter().filter(|x| **x == 2).count();
    (ones * twos) as i32
}

pub fn part_two(input: &str, width: i32, height: i32) {
    let area = width * height;
    let digits = get_digits(input);
    let layers: Vec<&[i32]> = digits.chunks(area as usize).collect();
    let mut image = vec![" "; area as usize];
    for layer in layers.iter().rev() {
        for i in 0..layer.len() {
            let pixel = layer[i];
            match pixel {
                0 => image[i] = " ",
                1 => image[i] = "X",
                _ => (),
            }
        }
    }
    output_image(&image, width, height);
}

Benchmarks

2019 - Day 08 - Part 1 time: 407.671µs
2019 - Day 08 - Part 2 time: 559.253µs

Feedback or Questions?

I don't have a direct way to leave comments on posts. But if you want to give some feedback or have some questions you can contact in other ways.

©2019–2021 Severin Kaderli