aoc/year2022/day08.rs
1//! # Treetop Tree House
2//!
3//! Part one is solved with an efficient `O(n)` algorithm. Part two is also solved with an efficient
4//! `O(n)` algorithm, using a bit manipulation trick to make the complexity independent of the
5//! number of digits.
6const ONES: u64 = 0x0041041041041041;
7const MASK: u64 = 0x0fffffffffffffc0;
8
9type Input = (usize, Vec<i8>);
10
11/// Convert a 2D grid of ASCII digits into a 1D `vec` of heights.
12///
13/// Each height is multiplied by 6. For part one this makes no difference, but for part two this
14/// helps with the bit manipulation.
15///
16/// To convert from 2D coordinates to an index, the formula is `y * width + x`. For the sample grid
17/// of width 5, the top middle point at `(2, 0)` is at index `0 * 5 + 2 = 2` and the point directly
18/// below `(2, 1)` is at index `1 * 5 + 2 = 7`.
19///
20/// Using a 1D `vec` instead of a `vec` of `vec`s is faster for 2 reasons:
21/// * Avoids an intermediate pointer lookup for each access.
22/// * Better cache locality as the memory locations are adjacent and not potentially scattered all
23/// over the heap.
24pub fn parse(input: &str) -> Input {
25 let raw: Vec<_> = input.lines().collect();
26 let width = raw[0].len();
27 let mut digits = Vec::with_capacity(raw.len() * width);
28
29 for line in &raw {
30 digits.extend(line.bytes().map(|b| 6 * (b - b'0') as i8));
31 }
32
33 (width, digits)
34}
35
36/// Calculate visible trees using a rolling maximum for each row and column in left, right, up
37/// and down directions.
38///
39/// Using the top row of the sample and going left to right:
40///
41/// | Tree | Max | Visible |
42/// |---|---|---|
43/// | 3 | -1 | true |
44/// | 0 | 3 | false |
45/// | 3 | 3 | false |
46/// | 7 | 3 | true |
47///
48/// The last tree in each row and column doesn't need to be checked since it's covered
49/// by the loop in the opposite direction.
50///
51/// A tree is visible if it can be seen from any direction. As a minor optimization, rather
52/// than have 4 separate loop pairs, the left, right, up and down loops are all rolled into
53/// one pair, to amortize the cost of loop logic.
54///
55/// The 4 corner trees don't need to be checked since they're always visible
56/// so they're added directly to the total.
57pub fn part1(input: &Input) -> usize {
58 let (width, digits) = input;
59 let width = *width;
60 let mut visible = vec![false; digits.len()];
61
62 for i in 1..(width - 1) {
63 let mut maxes = [-1; 4];
64
65 for j in 0..(width - 1) {
66 let k = width - j - 1;
67 // Left, right, top and bottom
68 let indices = [i * width + j, i * width + k, j * width + i, k * width + i];
69
70 for (index, max) in indices.into_iter().zip(&mut maxes) {
71 if digits[index] > *max {
72 visible[index] = true;
73 *max = digits[index];
74 }
75 }
76 }
77 }
78
79 4 + visible.iter().filter(|&&b| b).count()
80}
81
82/// Calculate the distance visible in each direction by using 10 rolling maximum values for each
83/// height packed into a single `u64`.
84///
85/// Part two is similar to part one, but instead of keeping a single maximum for each direction, we
86/// need to keep an *array* of 10 values, one for each possible height.
87///
88/// For each tree its score is the current value at the same index as its height. Then we increment
89/// the value of previously seen trees greater than the current height by one
90/// and reset the values of trees less than or equal to the current height to one.
91///
92/// We skip processing the edge and corner trees. Strictly speaking their score should be zero, but
93/// as the maximum value will always be greater than or equal to one, it's fine to leave them
94/// bulk initialized to one.
95///
96/// Using the fourth row of the sample and going left to right:
97///
98/// | Tree | Scenic Array | Score |
99/// |---|---|---|
100/// | 3 | [1, 1, 1, (1), 1, 1, 1, 1, 1, 1] | 1
101/// | 5 | [1, 1, 1, 1, 2, (2), 2, 2, 2, 2] | 2
102/// | 4 | [1, 1, 1, 1, (1), 1, 3, 3, 3, 3] | 1
103///
104/// Instead of using an array and iterating over it to update the values, we can achieve the same
105/// result much faster by packing the ten values into a single `u64` in blocks of 6 bits. 6 bits
106/// gives a maximum value of `2⁶ = 64` that's a bit of a gamble. It's less than the maximum
107/// possible value of 98 that could be theoretically encountered but should work for most inputs.
108///
109/// To obtain the current value we right shift by the current height times 6 (this is why we
110/// multiplied by 6 in the [`parse`] function) and mask only the least significant 6 bits.
111///
112/// To update the next value, we first use [`MASK`] left shifted to zero out all bits less than
113/// or equal to the current height then add 1 to all values in parallel using the [`ONES`] pattern.
114///
115/// For example, going from 3 to 5 in the sample above:
116/// ```none
117/// scenic: 000001_000001_000001_000001_000001_000001_000001_000001_000001_000001
118/// mask: 111111_111111_111111_111111_111111_111111_000000_000000_000000_000000
119/// scenic & mask: 000001_000001_000001_000001_000001_000001_000000_000000_000000_000000
120/// scenic + ones: 000010_000010_000010_000010_000010_000010_000001_000001_000001_000001
121/// ```
122pub fn part2(input: &Input) -> u64 {
123 let (width, digits) = input;
124 let width = *width;
125 let mut scenic = vec![1; digits.len()];
126
127 for i in 1..(width - 1) {
128 let mut maxes = [ONES; 4];
129
130 for j in 1..(width - 1) {
131 let k = width - j - 1;
132 // Left, right, top and bottom
133 let indices = [i * width + j, i * width + k, j * width + i, k * width + i];
134
135 for (index, max) in indices.into_iter().zip(&mut maxes) {
136 scenic[index] *= (*max >> digits[index]) & 0x3f;
137 *max = (*max & (MASK << digits[index])) + ONES;
138 }
139 }
140 }
141
142 *scenic.iter().max().unwrap()
143}