Skip to main content

aoc/year2023/
day14.rs

1//! # Parabolic Reflector Dish
2//!
3//! To solve part two we look for a cycle where the dish returns to a previously seen state.
4//! By storing each dish and an index in a `HashMap` we can calculate the offset and length of the
5//! cycle then use that to find the state at the billionth step.
6//!
7//! Calculating the state needs to be done sequentially so we use some tricks to make it as fast as
8//! possible.
9//!
10//! First the location of each ball is stored in a `vec`. My input had ~2,000 balls compared to
11//! 10,000 grid squares total, so this approach reduces the amount of data to scan by 5x. The 2D
12//! coordinates are converted to a 1D number, for example the index of a ball on the second row
13//! second column would be 1 × 100 + 1 = 101.
14//!
15//! Next for each possible tilt orientation (north, south, east and west) an approach similar to a
16//! prefix sum is used. Each edge or fixed rock is assigned an index. We expand the grid by 2 in
17//! each direction (one for each edge) to handle the edges. For example, using west (left):
18//!
19//! ```none
20//! ..#.#..
21//! ```
22//!
23//! is represented in `fixed_west` as (noticing the extra 0 for the left edge):
24//!
25//! ```none
26//! 0 0 0 1 1 2 2 2
27//! ```
28//!
29//! The number of balls that come to rest against each fixed point is counted, for example:
30//!
31//! ```none
32//! OO#.#OO
33//! ```
34//!
35//! is stored in `roll_west` similar to:
36//!
37//! ```none
38//! 2 0 2
39//! ```
40//!
41//! This approach has two huge advantages:
42//!
43//! First, the number of balls resting against each fixed point completely represents the state of
44//! the grid in a very compact format. For example, my input has ~1600 fixed points. Using 2 bytes
45//! per point needs 3.2K total to represent the grid, compared to 100 × 100 = 10K for the simple
46//! approach. 3x less data is 3x faster to hash when storing states in a `HashMap` looking for
47//! duplicates.
48//!
49//! Second, calculating the new position of a ball is very fast. For each ball:
50//!
51//! * Use `fixed_*` to lookup the index in the corresponding `roll_*` vec.
52//! * This stores the current index of the last ball resting against that fixed point.
53//! * Increment this value by ±1 for horizontal movement or ±width for vertical movement and then
54//!   update the new location of this ball.
55//!
56//! For example, tilting a single row west, processing each ball from left to right where each line
57//! represents the new state would look like:
58//!
59//! ```none
60//! grid              rounded         fixed_west                       roll_west
61//! .O#..O.OO.#..O    [1 5 7 8 13]    [0 0 1 1 1 1 1 1 1 1 2 2 2 2]    [-1 2 10]
62//! O.#..O.OO.#..O    [0 5 7 8 13]    [0 0 1 1 1 1 1 1 1 1 2 2 2 2]    [0 2 10]
63//! O.#O...OO.#..O    [0 3 7 8 13]    [0 0 1 1 1 1 1 1 1 1 2 2 2 2]    [0 3 10]
64//! O.#OO...O.#..O    [0 3 4 8 13]    [0 0 1 1 1 1 1 1 1 1 2 2 2 2]    [0 4 10]
65//! O.#OOO....#..O    [0 3 4 5 13]    [0 0 1 1 1 1 1 1 1 1 2 2 2 2]    [0 5 10]
66//! O.#OOO....#O..    [0 3 4 5 11]    [0 0 1 1 1 1 1 1 1 1 2 2 2 2]    [0 5 11]
67//! ```
68use crate::util::grid::*;
69use crate::util::hash::*;
70use crate::util::point::*;
71
72pub struct Input {
73    width: i32,
74    height: i32,
75    // Index of each ball.
76    rounded: Vec<i16>,
77    // Index into corresponding `roll_` vec for each possible grid location.
78    fixed_north: Vec<i16>,
79    fixed_west: Vec<i16>,
80    fixed_south: Vec<i16>,
81    fixed_east: Vec<i16>,
82    // The current index of the ball resting against each fixed point.
83    roll_north: Vec<i16>,
84    roll_west: Vec<i16>,
85    roll_south: Vec<i16>,
86    roll_east: Vec<i16>,
87}
88
89pub fn parse(input: &str) -> Input {
90    // Expand the grid by 2 in each direction to handle edges the same way as fixed points.
91    let inner = Grid::parse(input);
92    let mut grid = Grid::new(inner.width + 2, inner.height + 2, b'#');
93
94    // Copy inner grid.
95    for src in inner.points() {
96        let dst = src + Point::new(1, 1);
97        grid[dst] = inner[src];
98    }
99
100    let mut rounded = Vec::new();
101    let mut north = grid.same_size_with(0);
102    let mut west = grid.same_size_with(0);
103    let mut south = grid.same_size_with(0);
104    let mut east = grid.same_size_with(0);
105    let mut roll_north = Vec::new();
106    let mut roll_west = Vec::new();
107    let mut roll_south = Vec::new();
108    let mut roll_east = Vec::new();
109
110    // For each direction, store the next index that a ball will roll to in that direction.
111    let update = |fixed: &mut Grid<i16>, roll: &mut Vec<i16>, point: Point| {
112        if grid[point] == b'#' {
113            roll.push((grid.width * point.y + point.x) as i16);
114        }
115        fixed[point] = (roll.len() - 1) as i16;
116    };
117
118    // North and south are intentionally iterated in column-major order, south from the bottom.
119    for x in 0..grid.width {
120        for y in 0..grid.height {
121            update(&mut north, &mut roll_north, Point::new(x, y));
122            update(&mut south, &mut roll_south, Point::new(x, grid.height - 1 - y));
123        }
124    }
125
126    // West and east are iterated in row-major order, east from the right. Also store the
127    // starting index of each rounded ball.
128    for point in grid.points() {
129        if grid[point] == b'O' {
130            rounded.push((grid.width * point.y + point.x) as i16);
131        }
132        update(&mut west, &mut roll_west, point);
133        update(&mut east, &mut roll_east, Point::new(grid.width - 1 - point.x, point.y));
134    }
135
136    Input {
137        width: grid.width,
138        height: grid.height,
139        rounded,
140        fixed_north: north.bytes,
141        fixed_west: west.bytes,
142        fixed_south: south.bytes,
143        fixed_east: east.bytes,
144        roll_north,
145        roll_west,
146        roll_south,
147        roll_east,
148    }
149}
150
151pub fn part1(input: &Input) -> i32 {
152    let Input { width, height, .. } = *input;
153    let Input { fixed_north, roll_north, .. } = input;
154
155    // Tilt north only once.
156    let mut result = 0;
157    let rounded = &mut input.rounded.clone();
158    let state = tilt(rounded, fixed_north, roll_north, width as i16);
159
160    // Find vertical distance of each ball from the bottom, remembering that the grid is 2 bigger.
161    for (&a, &b) in roll_north.iter().zip(&state) {
162        for index in (a..b).step_by(width as usize) {
163            let y = (index as i32) / width;
164            result += height - 2 - y;
165        }
166    }
167
168    result
169}
170
171pub fn part2(input: &Input) -> i32 {
172    let Input { width, height, .. } = *input;
173
174    let rounded = &mut input.rounded.clone();
175    let mut seen = FastMap::with_capacity(100);
176
177    // Simulate tilting until a cycle is found.
178    let (start, end) = loop {
179        tilt(rounded, &input.fixed_north, &input.roll_north, width as i16);
180        tilt(rounded, &input.fixed_west, &input.roll_west, 1);
181        tilt(rounded, &input.fixed_south, &input.roll_south, -(width) as i16);
182        let state = tilt(rounded, &input.fixed_east, &input.roll_east, -1);
183
184        if let Some(previous) = seen.insert(state, seen.len()) {
185            break (previous, seen.len());
186        }
187    };
188
189    // Find the index of the state after 1 billion repetitions.
190    let offset = 1_000_000_000 - 1 - start;
191    let cycle_width = end - start;
192    let remainder = offset % cycle_width;
193    let target = start + remainder;
194
195    let (state, _) = seen.iter().find(|&(_, &i)| i == target).unwrap();
196    let mut result = 0;
197
198    for (&a, &b) in input.roll_east.iter().zip(state.iter()) {
199        // Number of balls resting against the fixed point.
200        let n = (a - b) as i32;
201        // Distance from bottom.
202        let y = (a as i32) / width;
203        // Total load.
204        result += n * (height - 1 - y);
205    }
206
207    result
208}
209
210/// Very fast calculation of new state after tilting in the specified direction.
211fn tilt(rounded: &mut [i16], fixed: &[i16], roll: &[i16], direction: i16) -> Vec<i16> {
212    let mut state = roll.to_vec();
213
214    for rock in rounded {
215        let index = fixed[*rock as usize] as usize;
216        state[index] += direction;
217        *rock = state[index];
218    }
219
220    state
221}