aoc/year2022/day17.rs
1//! # Pyroclastic Flow
2//!
3//! ## Part One
4//!
5//! For speed we encode each rock shape as binary bits so that we can use bitwise logic to check
6//! for collisions. Each rock is encoded top to bottom and left to right. For example:
7//!
8//! ```none
9//! # 00010000 0x10
10//! ### => 00111000 => 0x38 => 0x00103810
11//! # 00010000 0x10
12//! ```
13//!
14//! The bits are shifted 2 away from the left wall. Walls are also encoded in binary, overlapping
15//! the left and right walls (no rock will ever collide first with a wall and its top row):
16//!
17//! ```none
18//! 100000001
19//! 100000001 => 0x01010101
20//! 100000001
21//! ```
22//!
23//! We store the accumulated tower efficiently as a vec of `u8` including the floor at index
24//! zero as a special pattern of `11111111`.
25//!
26//! We use bitwise AND to check for collisions between the rock, the walls and the existing tower
27//! in one operation.
28//!
29//! ## Part Two
30//!
31//! Since there's no reasonable way to analytically predict the height after some `n` rocks
32//! and brute force would take too long, we can assume that there must be a
33//! [cycle](https://en.wikipedia.org/wiki/Cycle_(graph_theory)) in the output.
34//!
35//! We choose an arbitrary length and generate a sequence of that size then search
36//! for repeating patterns. Once we find the length of the cycle then we can extrapolate for
37//! any `n` greater than the start of the cycle.
38use std::iter::once;
39
40/// Encode pieces one row per byte, highest row in the most significant position.
41const FLOOR: u8 = 0xff;
42const WALLS: u32 = 0x01010101;
43const ROCKS: [Rock; 5] = [
44 Rock { size: 1, shape: 0x0000003c },
45 Rock { size: 3, shape: 0x00103810 },
46 Rock { size: 3, shape: 0x00080838 },
47 Rock { size: 4, shape: 0x20202020 },
48 Rock { size: 2, shape: 0x00003030 },
49];
50
51struct Rock {
52 size: usize,
53 shape: u32,
54}
55
56pub fn parse(input: &str) -> &[u8] {
57 input.trim().as_bytes()
58}
59
60pub fn part1(input: &[u8]) -> usize {
61 simulate(input).nth(2021).unwrap()
62}
63
64pub fn part2(input: &[u8]) -> usize {
65 // We make two complete [SWAGs](https://en.wikipedia.org/wiki/Scientific_wild-ass_guess):
66 // * 1000 row deltas are enough to form a unique prefix
67 // * The tower pattern will repeat in a cycle in the first 5000 rows.
68 let guess = 1000;
69 let height: Vec<_> = simulate(input).take(5 * guess).collect();
70 // We compare based on the *delta* between rows instead of absolute heights.
71 let deltas: Vec<_> =
72 once(height[0]).chain(height.array_windows().map(|[a, b]| b - a)).collect();
73
74 // Simple brute force check, instead of a
75 // [cycle detection](https://en.wikipedia.org/wiki/Cycle_detection) algorithm.
76 let end = deltas.len() - guess;
77 let needle = &deltas[end..];
78 let start = deltas.windows(guess).position(|w| w == needle).unwrap();
79
80 // Now that we know when the cycle repeats, we can work out the height for any arbitrary
81 // number of rocks after that point.
82 let cycle_height = height[end] - height[start];
83 let cycle_width = end - start;
84 let offset = 1_000_000_000_000 - 1 - start;
85 let quotient = offset / cycle_width;
86 let remainder = offset % cycle_width;
87 (quotient * cycle_height) + height[start + remainder]
88}
89
90/// Returns an endless iterator of the tower's height after each rock comes to rest.
91fn simulate(input: &[u8]) -> impl Iterator<Item = usize> {
92 // 13,000 is the maximum possible height that the tower could reach after 5000 rocks.
93 let mut tower = vec![0; 13_000];
94 let mut height = 0;
95 tower[0] = FLOOR;
96
97 // Rocks and jets repeat endlessly.
98 let mut jets = input.iter().copied().cycle();
99
100 ROCKS.iter().cycle().map(move |&Rock { size, mut shape }| {
101 let mut chunk = WALLS;
102 // Start 3 rows above the current top of the tower.
103 let mut index = height + 3;
104
105 loop {
106 let jet = jets.next().unwrap();
107 let candidate = if jet == b'<' { shape.rotate_left(1) } else { shape.rotate_right(1) };
108 // Check for a horizontal collision (this does not prevent downwards movement).
109 if candidate & chunk == 0 {
110 shape = candidate;
111 }
112
113 // The neat part of using bitwise AND to compare is that we can check all four
114 // rows in a single operation, including both walls and the existing tower.
115 chunk = (chunk << 8) | WALLS | u32::from(tower[index]);
116
117 if shape & chunk == 0 {
118 // Keep falling.
119 index -= 1;
120 } else {
121 // Add the new piece to the tower.
122 let bytes = shape.to_le_bytes();
123 tower[index + 1] |= bytes[0];
124 tower[index + 2] |= bytes[1];
125 tower[index + 3] |= bytes[2];
126 tower[index + 4] |= bytes[3];
127 // Rock may have fallen far enough to not add any additional height.
128 height = height.max(index + size);
129 break height;
130 }
131 }
132 })
133}