advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git

day-08.rs (1652B)

    1 fn main() {
    2     let input = std::fs::read_to_string("input.txt")
    3         .unwrap()
    4         .trim()
    5         .chars()
    6         .map(|op| op.to_digit(10).unwrap() as usize)
    7         .collect::<Vec<usize>>();
    8     println!("Rust:");
    9     println!("Part 1: {}", part_1(&input));
   10     println!("Part 2: ");
   11     part_2(&input);
   12 }
   13 
   14 fn part_1(input: &Vec<usize>) -> usize {
   15     let width = 25;
   16     let height = 6;
   17     let num_layer = input.len() / (width * height);
   18     let mut num_0 = vec![0; num_layer];
   19     let mut num_1 = vec![0; num_layer];
   20     let mut num_2 = vec![0; num_layer];
   21 
   22     input.iter().enumerate().for_each(|(i, val)| {
   23         let layer = i / (width * height);
   24         match val {
   25             0 => num_0[layer] += 1,
   26             1 => num_1[layer] += 1,
   27             2 => num_2[layer] += 1,
   28             _ => unreachable!(),
   29         }
   30     });
   31 
   32     let min_0_layer = num_0
   33         .iter()
   34         .enumerate()
   35         .min_by_key(|&(_, value)| value)
   36         .unwrap()
   37         .0;
   38 
   39     num_1[min_0_layer] * num_2[min_0_layer]
   40 }
   41 
   42 fn part_2(input: &Vec<usize>) {
   43     let width = 25;
   44     let height = 6;
   45     let num_layer = input.len() / (width * height);
   46     let mut image = vec![2; width * height];
   47 
   48     for i in 0..image.len() {
   49         // Find first non-transparent cell.
   50         let mut layer = 0;
   51         while image[i] == 2 && layer < num_layer {
   52             image[i] = input[layer * width * height + i];
   53             layer += 1;
   54         }
   55     }
   56 
   57     image.chunks_exact(width).for_each(|line| {
   58         line.iter().for_each(|x| match x {
   59             1 => print!("██"),
   60             _ => print!("  "),
   61         });
   62         println!("");
   63     });
   64 }