Skip to main content

advent_of_code/year2016/
day18.rs

1use crate::input::Input;
2
3pub fn solve(input: &Input) -> Result<u32, String> {
4    let mut row = input
5        .text
6        .as_bytes()
7        .iter()
8        .map(|&b| b == b'^')
9        .collect::<Vec<_>>();
10
11    let mut safe_count = row.iter().filter(|&&b| !b).count();
12    let mut next_row = vec![false; row.len()];
13
14    for _count in 1..input.part_values(40, 400_000) {
15        for i in 0..next_row.len() {
16            let left_is_trap = if i == 0 { false } else { row[i - 1] };
17            let center_is_trap = row[i];
18            let right_is_trap = if i == next_row.len() - 1 {
19                false
20            } else {
21                row[i + 1]
22            };
23
24            // "Then, a new tile is a trap only in one of the following situations":
25            // - Its left and center tiles are traps, but its right tile is not.
26            // - Its center and right tiles are traps, but its left tile is not.
27            // - Only its left tile is a trap.
28            // - Only its right tile is a trap."
29            next_row[i] = matches!(
30                (left_is_trap, center_is_trap, right_is_trap),
31                (true, true | false, false) | (false, true | false, true)
32            );
33            if !next_row[i] {
34                safe_count += 1;
35            }
36        }
37
38        std::mem::swap(&mut row, &mut next_row);
39    }
40
41    Ok(safe_count as u32)
42}
43
44#[test]
45pub fn tests() {
46    let real_input = include_str!("day18_input.txt");
47    test_part_one!(real_input => 2035);
48    test_part_two!(real_input => 20_000_577);
49}