Skip to main content

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        let (_, coordinates) = block.split_once('\n').unwrap();
114        let beacons: Vec<_> = coordinates.iter_signed().chunk::<3>().map(Point3D::parse).collect();
115
116        // Include indices of the points so that we can match translation and rotation for
117        // points that have the same signature. Use indices so that we don't need to recalculate
118        // signature when rotating and translating a beacon from unknown to known.
119        let mut signature = FastMap::with_capacity(1_000);
120        for i in 0..(beacons.len() - 1) {
121            for j in (i + 1)..beacons.len() {
122                signature.insert(beacons[i].euclidean(beacons[j]), [i, j]);
123            }
124        }
125
126        Self { beacons, signature }
127    }
128}
129
130/// Returns the correct orientation and translation to link a new scanner to an existing
131/// reference scanner.
132#[derive(Clone, Copy)]
133struct Found {
134    orientation: usize,
135    translation: Point3D,
136}
137
138/// Represents a known scanner with the same orientation and a known translation from
139/// our initial reference scanner.
140pub struct Located {
141    beacons: Vec<Point3D>,
142    signature: FastMap<i32, [usize; 2]>,
143    oriented: FastSet<Point3D>,
144    translation: Point3D,
145}
146
147impl Located {
148    fn new(scanner: Scanner, found: Found) -> Self {
149        let Scanner { beacons, signature } = scanner;
150        let Found { orientation, translation } = found;
151
152        // Rotate and translate the beacons by the offset of this scanner from the reference, so
153        // that we can build "chains" of scanners, for example A -> B -> C, where A and B overlap,
154        // B and C overlap, but not A and C.
155        let beacons: Vec<_> =
156            beacons.into_iter().map(|b| b.transform(orientation) + translation).collect();
157        let oriented = beacons.iter().copied().collect();
158
159        Self { beacons, signature, oriented, translation }
160    }
161}
162
163/// Convert the raw input into a vec of unknown scanners, then do all the heavy lifting of figuring
164/// out the relative orientations and translations of each scanner.
165///
166/// First choose an arbitrary scanner that determines the reference orientation and that we
167/// decide is located at the origin.
168///
169/// Then for each remaining unknown scanner, check if the signature indicates a potential
170/// match. If confirmed, we determine the orientation and translation then add the scanner
171/// to a todo list to recheck against other unknown scanners.
172///
173/// This works for situations such as A -> B -> C, where A and B overlap, B and C overlap, but not
174/// A and C.
175pub fn parse(input: &str) -> Vec<Located> {
176    let mut unknown: Vec<_> = input.split("\n\n").map(Scanner::parse).collect();
177    let scanner = unknown.pop().unwrap();
178    let found = Found { orientation: 0, translation: Point3D(0, 0, 0) };
179
180    let mut todo = vec![Located::new(scanner, found)];
181    let mut done = Vec::new();
182
183    while let Some(known) = todo.pop() {
184        let mut next_unknown = Vec::new();
185
186        while let Some(scanner) = unknown.pop() {
187            match check(&known, &scanner) {
188                Some(found) => todo.push(Located::new(scanner, found)),
189                None => next_unknown.push(scanner),
190            }
191        }
192
193        done.push(known);
194        unknown = next_unknown;
195    }
196
197    done
198}
199
200/// Calculate the total number of distinct beacons.
201pub fn part1(input: &[Located]) -> usize {
202    input.iter().flat_map(|located| &located.beacons).collect::<FastSet<_>>().len()
203}
204
205/// Calculate the maximum Manhattan distance between any two scanners.
206pub fn part2(input: &[Located]) -> i32 {
207    // This solution uses the usual quadratic pairing of every point. This is okay because
208    // the set is not terribly large, and the runtime here is dwarfed by the earlier runtime
209    // taken to get the coordinates in place. However, a linear solution is also possible:
210    // https://www.reddit.com/r/adventofcode/comments/rygnl8/2021_day_19_part_2pseudocode_speeding_up/
211    input
212        .iter()
213        .flat_map(|a| input.iter().map(|b| a.translation.manhattan(b.translation)))
214        .max()
215        .unwrap()
216}
217
218/// At least 66 Euclidean distances must overlap for a potential match.
219fn check(known: &Located, scanner: &Scanner) -> Option<Found> {
220    let mut matching = 0;
221
222    for key in known.signature.keys() {
223        if scanner.signature.contains_key(key) {
224            matching += 1;
225            if matching == 66 {
226                // Choose any arbitrary pair of points that have a matching signature.
227                let [a, b] = known.signature[key];
228                let [x, y] = scanner.signature[key];
229                let points =
230                    [known.beacons[a], known.beacons[b], scanner.beacons[x], scanner.beacons[y]];
231                return detailed_check(known, scanner, points);
232            }
233        }
234    }
235
236    None
237}
238
239/// The correct translation and orientation is found when we have at least 12 beacons overlapping.
240fn detailed_check(known: &Located, scanner: &Scanner, points: [Point3D; 4]) -> Option<Found> {
241    let [a, b, x, y] = points;
242    let delta = a - b;
243
244    (0..24).find_map(|orientation| {
245        let rotate_x = x.transform(orientation);
246        let rotate_y = y.transform(orientation);
247
248        let translation = if rotate_x - rotate_y == delta {
249            b - rotate_y
250        } else if rotate_y - rotate_x == delta {
251            b - rotate_x
252        } else {
253            return None;
254        };
255
256        let count = scanner
257            .beacons
258            .iter()
259            .filter(|beacon| {
260                known.oriented.contains(&(beacon.transform(orientation) + translation))
261            })
262            .take(12)
263            .count();
264
265        (count == 12).then_some(Found { orientation, translation })
266    })
267}