Skip to main content

aoc/year2018/
day20.rs

1//! # A Regular Map
2//!
3//! Simple solution taking advantage of a controversial property of the input. After taking any
4//! branch it's assumed that we can return to the pre-branch position. This does *not* hold for
5//! general inputs, as it's easy to construct paths which violate this constraint.
6//!
7//! We use a stack to save the position before a branch, pushing whenever an opening `(` is
8//! encountered then popping whenever the closing `)` is found. Additionally, we assume that
9//! the location will never move more than 55 rooms from the starting location in order to use
10//! a fixed-size array to hold the minimum distance to any room.
11
12/// 55 rooms in each direction gives a width and height of 110.
13const SIZE: usize = 110;
14
15type Input = (u32, usize);
16
17pub fn parse(input: &str) -> Input {
18    // Start in the center.
19    let mut index = SIZE / 2 * SIZE + SIZE / 2;
20    let mut grid = vec![u32::MAX; SIZE * SIZE];
21    let mut stack = Vec::with_capacity(500);
22    let mut part_one = 0;
23
24    grid[index] = 0;
25
26    // Change in index for each direction.
27    let mut delta = [0; 256];
28    delta[b'N' as usize] = SIZE.wrapping_neg();
29    delta[b'S' as usize] = SIZE;
30    delta[b'W' as usize] = 1_usize.wrapping_neg();
31    delta[b'E' as usize] = 1;
32
33    for b in input.bytes() {
34        let distance = grid[index];
35
36        match b {
37            b'(' => stack.push(index),
38            b'|' => index = *stack.last().unwrap(),
39            b')' => index = stack.pop().unwrap(),
40            _ => index = index.wrapping_add(delta[b as usize]),
41        }
42
43        grid[index] = grid[index].min(distance + 1);
44        part_one = part_one.max(grid[index]);
45    }
46
47    let part_two = grid.iter().filter(|d| (1000..u32::MAX).contains(d)).count();
48    (part_one, part_two)
49}
50
51pub fn part1(input: &Input) -> u32 {
52    input.0
53}
54
55pub fn part2(input: &Input) -> usize {
56    input.1
57}