aoc/year2021/day19.rs
1//! # Beacon Scanner
2//!
3//! A brute force approach is:
4//! * Choose an arbitrary starting scanner, then add its beacons to a "known" set.
5//! * For each remaining scanner, then for each of its possible 24 rotations, check its beacons by
6//! translating against every other beacon in the known set.
7//! * If we find a match of 12 or more overlapping beacons, then merge the beacons into the known
8//! set.
9//!
10//! This approach will work but is a little slow as the number of potential comparisons is quite
11//! high. We can speed things up by first creating a "signature" for each beacon similar to how
12//! a hash is computed for an item in a hash map. Ideally this signature should be the same no
13//! matter what the rotation of the beacons, as this will reduce the number of comparisons by a
14//! factor of 24.
15//!
16//! The set of Euclidean distance squared between all beacons is a good choice, as it's invariant
17//! under rotation and translation, quick to calculate and a good discriminant. To check for an
18//! overlap of 12 beacons, we look for an overlap of at least 12 × 11 / 2 = 66 distances.
19//! (12 beacons gives 12 × 11 = 132 pairs of distances but divided by 2 since the distance from
20//! a -> b is the same as b -> a).
21//!
22//! An overlap indicates a potential match, but we need to confirm by checking the beacons against
23//! each other in two steps. First confirming orientation by matching the deltas between
24//! points, then by translating the beacons until 12 overlap.
25use std::ops::{Add, Sub};
26
27use crate::util::hash::*;
28use crate::util::iter::*;
29use crate::util::parse::*;
30
31/// Stores coordinates in x, y, z order.
32#[derive(Clone, Copy, Eq, Hash, PartialEq)]
33struct Point3D(i32, i32, i32);
34
35impl Point3D {
36 fn parse([x, y, z]: [i32; 3]) -> Self {
37 Self(x, y, z)
38 }
39
40 /// There are 24 possible 3D rotations of each point in increments of 90 degrees.
41 fn transform(self, index: usize) -> Self {
42 let Self(x, y, z) = self;
43 match index {
44 0 => Self(x, y, z),
45 1 => Self(x, z, -y),
46 2 => Self(x, -z, y),
47 3 => Self(x, -y, -z),
48 4 => Self(-x, -z, -y),
49 5 => Self(-x, y, -z),
50 6 => Self(-x, -y, z),
51 7 => Self(-x, z, y),
52 8 => Self(y, z, x),
53 9 => Self(y, -x, z),
54 10 => Self(y, x, -z),
55 11 => Self(y, -z, -x),
56 12 => Self(-y, x, z),
57 13 => Self(-y, z, -x),
58 14 => Self(-y, -z, x),
59 15 => Self(-y, -x, -z),
60 16 => Self(z, x, y),
61 17 => Self(z, y, -x),
62 18 => Self(z, -y, x),
63 19 => Self(z, -x, -y),
64 20 => Self(-z, y, x),
65 21 => Self(-z, -x, y),
66 22 => Self(-z, x, -y),
67 23 => Self(-z, -y, -x),
68 _ => unreachable!(),
69 }
70 }
71
72 /// No need to take the square root as it's faster and easier to just use the integer
73 /// value of the distance squared directly.
74 fn euclidean(self, other: Self) -> i32 {
75 let Self(dx, dy, dz) = self - other;
76 dx * dx + dy * dy + dz * dz
77 }
78
79 fn manhattan(self, other: Self) -> i32 {
80 let Self(dx, dy, dz) = self - other;
81 dx.abs() + dy.abs() + dz.abs()
82 }
83}
84
85/// Implement operators for points so that we can write `a + b` or `a - b`.
86impl Add for Point3D {
87 type Output = Self;
88
89 fn add(self, rhs: Self) -> Self {
90 Self(self.0 + rhs.0, self.1 + rhs.1, self.2 + rhs.2)
91 }
92}
93
94impl Sub for Point3D {
95 type Output = Self;
96
97 fn sub(self, rhs: Self) -> Self {
98 Self(self.0 - rhs.0, self.1 - rhs.1, self.2 - rhs.2)
99 }
100}
101
102/// Represents an unknown scanner that could be at any orientation and translation
103/// from our initial reference scanner.
104struct Scanner {
105 beacons: Vec<Point3D>,
106 signature: FastMap<i32, [usize; 2]>,
107}
108
109impl Scanner {
110 /// Calculate the signature as the set of Euclidean distance squared between every possible
111 /// pair of beacons.
112 fn parse(block: &str) -> Self {
113 // Each beacon header results in 5 mangled numbers at the start that should be skipped.
114 let beacons: Vec<_> =
115 block.iter_signed().skip(5).chunk::<3>().map(Point3D::parse).collect();
116
117 // Include indices of the points so that we can match translation and rotation for
118 // points that have the same signature. Use indices so that we don't need to recalculate
119 // signature when rotating and translating a beacon from unknown to known.
120 let mut signature = FastMap::with_capacity(1_000);
121 for i in 0..(beacons.len() - 1) {
122 for j in (i + 1)..beacons.len() {
123 signature.insert(beacons[i].euclidean(beacons[j]), [i, j]);
124 }
125 }
126
127 Self { beacons, signature }
128 }
129}
130
131/// Returns the correct orientation and translation to link a new scanner to an existing
132/// reference scanner.
133#[derive(Clone, Copy)]
134struct Found {
135 orientation: usize,
136 translation: Point3D,
137}
138
139/// Represents a known scanner with the same orientation and a known translation from
140/// our initial reference scanner.
141pub struct Located {
142 beacons: Vec<Point3D>,
143 signature: FastMap<i32, [usize; 2]>,
144 oriented: FastSet<Point3D>,
145 translation: Point3D,
146}
147
148impl Located {
149 fn new(scanner: Scanner, found: Found) -> Self {
150 let Scanner { beacons, signature } = scanner;
151 let Found { orientation, translation } = found;
152
153 // Rotate and translate the beacons by the offset of this scanner from the reference, so
154 // that we can build "chains" of scanners, for example A -> B -> C, where A and B overlap,
155 // B and C overlap, but not A and C.
156 let beacons: Vec<_> =
157 beacons.into_iter().map(|b| b.transform(orientation) + translation).collect();
158 let oriented = beacons.iter().copied().collect();
159
160 Self { beacons, signature, oriented, translation }
161 }
162}
163
164/// Convert the raw input into a vec of unknown scanners, then do all the heavy lifting of figuring
165/// out the relative orientations and translations of each scanner.
166///
167/// First choose an arbitrary scanner that determines the reference orientation and that we
168/// decide is located at the origin.
169///
170/// Then for each remaining unknown scanner, check if the signature indicates a potential
171/// match. If confirmed, we determine the orientation and translation then add the scanner
172/// to a todo list to recheck against other unknown scanners.
173///
174/// This works for situations such as A -> B -> C, where A and B overlap, B and C overlap, but not
175/// A and C.
176pub fn parse(input: &str) -> Vec<Located> {
177 let mut unknown: Vec<_> = input.split("\n\n").map(Scanner::parse).collect();
178 let mut todo = Vec::new();
179 let mut done = Vec::new();
180
181 let scanner = unknown.pop().unwrap();
182 let found = Found { orientation: 0, translation: Point3D(0, 0, 0) };
183 todo.push(Located::new(scanner, found));
184
185 while let Some(known) = todo.pop() {
186 let mut next_unknown = Vec::new();
187
188 while let Some(scanner) = unknown.pop() {
189 match check(&known, &scanner) {
190 Some(found) => todo.push(Located::new(scanner, found)),
191 None => next_unknown.push(scanner),
192 }
193 }
194
195 done.push(known);
196 unknown = next_unknown;
197 }
198
199 done
200}
201
202/// Calculate the total number of distinct beacons.
203pub fn part1(input: &[Located]) -> usize {
204 input.iter().flat_map(|located| &located.beacons).collect::<FastSet<_>>().len()
205}
206
207/// Calculate the maximum Manhattan distance between any two scanners.
208pub fn part2(input: &[Located]) -> i32 {
209 // This solution uses the usual quadratic pairing of every point. This is okay because
210 // the set is not terribly large, and the runtime here is dwarfed by the earlier runtime
211 // taken to get the coordinates in place. However, a linear solution is also possible:
212 // https://www.reddit.com/r/adventofcode/comments/rygnl8/2021_day_19_part_2pseudocode_speeding_up/
213 input
214 .iter()
215 .flat_map(|a| input.iter().map(|b| a.translation.manhattan(b.translation)))
216 .max()
217 .unwrap()
218}
219
220/// At least 66 Euclidean distances must overlap for a potential match.
221fn check(known: &Located, scanner: &Scanner) -> Option<Found> {
222 let mut matching = 0;
223
224 for key in known.signature.keys() {
225 if scanner.signature.contains_key(key) {
226 matching += 1;
227 if matching == 66 {
228 // Choose any arbitrary pair of points that have a matching signature.
229 let [a, b] = known.signature[key];
230 let [x, y] = scanner.signature[key];
231 let points =
232 [known.beacons[a], known.beacons[b], scanner.beacons[x], scanner.beacons[y]];
233 return detailed_check(known, scanner, points);
234 }
235 }
236 }
237
238 None
239}
240
241/// The correct translation and orientation is found when we have at least 12 beacons overlapping.
242fn detailed_check(known: &Located, scanner: &Scanner, points: [Point3D; 4]) -> Option<Found> {
243 let [a, b, x, y] = points;
244 let delta = a - b;
245
246 for orientation in 0..24 {
247 let rotate_x = x.transform(orientation);
248 let rotate_y = y.transform(orientation);
249
250 let translation = if rotate_x - rotate_y == delta {
251 b - rotate_y
252 } else if rotate_y - rotate_x == delta {
253 b - rotate_x
254 } else {
255 continue;
256 };
257
258 let count = scanner
259 .beacons
260 .iter()
261 .filter(|beacon| {
262 known.oriented.contains(&(beacon.transform(orientation) + translation))
263 })
264 .take(12)
265 .count();
266
267 if count == 12 {
268 return Some(Found { orientation, translation });
269 }
270 }
271
272 None
273}