Skip to main content

aoc/year2023/
day24.rs

1//! # Never Tell Me The Odds
2//!
3//! ## Part One
4//!
5//! We find the intersection for each pair of hailstones by solving a pair of linear simultaneous
6//! equations in 2 unknowns:
7//!
8//! * `a` and `g` are the x positions of the pair of hailstones.
9//! * `b` and `h` are the y positions.
10//! * `d` and `j` are the x velocities.
11//! * `e` and `k` are the y velocities.
12//! * Let `t` and `u` be the times that the first and second hailstone respectively are at the
13//!   intersection point.
14//!
15//! Then we can write:
16//!
17//! * `a + dt = g + ju` => `dt - ju = g - a`
18//! * `b + et = h + ku` => `et - ku = h - b`
19//!
20//! In matrix form:
21//!
22//! ```none
23//! | d  -j ||u| = | g - a |
24//! | e  -k ||t|   | h - b |
25//! ```
26//!
27//! Solve by finding the inverse of the 2x2 matrix and premultiplying both sides. The inverse is:
28//!
29//! ```none
30//! ______1______ | -k  j |
31//! d(-k) - (-j)e | -e  d |
32//! ```
33//!
34//! Then we check that both times are non-negative and that the intersection point is inside the
35//! target area.
36//!
37//! ## Part Two
38//!
39//! First we choose 3 arbitrary hailstones. Then we subtract the position and velocity of
40//! the first to make the other two relative.
41//!
42//! The two hailstones will intercept a line leaving the origin. We can determine this line
43//! by intersecting the two planes that the hailstones' velocities lie in. These planes are
44//! defined by a normal vector orthogonal to the plane.
45//!
46//! This normal vector is the [cross product](https://en.wikipedia.org/wiki/Cross_product) of
47//! any two vectors that lie in the plane, in this case the velocity and also the vector from the
48//! origin to the starting location of the hailstone.
49//!
50//! The direction but not necessarily the magnitude of the velocity is then given by the cross
51//! product of the two normals.
52//!
53//! Given the rock direction we can calculate the times that the two hailstones are intercepted
54//! then use this to determine the original position of the rock, as long as the two times
55//! are different.
56use std::ops::{Add, RangeInclusive, Sub};
57
58use crate::util::iter::*;
59use crate::util::math::*;
60use crate::util::parse::*;
61
62const RANGE: RangeInclusive<i64> = 200_000_000_000_000..=400_000_000_000_000;
63
64#[derive(Clone, Copy)]
65struct Vector {
66    x: i128,
67    y: i128,
68    z: i128,
69}
70
71impl Add for Vector {
72    type Output = Self;
73
74    fn add(self, rhs: Self) -> Self {
75        Self { x: self.x + rhs.x, y: self.y + rhs.y, z: self.z + rhs.z }
76    }
77}
78
79impl Sub for Vector {
80    type Output = Self;
81
82    fn sub(self, rhs: Self) -> Self {
83        Self { x: self.x - rhs.x, y: self.y - rhs.y, z: self.z - rhs.z }
84    }
85}
86
87impl Vector {
88    fn cross(self, other: Self) -> Self {
89        let x = self.y * other.z - self.z * other.y;
90        let y = self.z * other.x - self.x * other.z;
91        let z = self.x * other.y - self.y * other.x;
92        Self { x, y, z }
93    }
94
95    // Changes the magnitude (but not direction) of the vector.
96    // Prevents numeric overflow.
97    fn gcd(self) -> Self {
98        let gcd = self.x.gcd(self.y).gcd(self.z);
99        Self { x: self.x / gcd, y: self.y / gcd, z: self.z / gcd }
100    }
101
102    fn sum(self) -> i128 {
103        self.x + self.y + self.z
104    }
105}
106
107pub fn parse(input: &str) -> Vec<[i64; 6]> {
108    input.iter_signed().chunk::<6>().collect()
109}
110
111pub fn part1(input: &[[i64; 6]]) -> u32 {
112    let mut result = 0;
113
114    for (index, &[a, b, _, c, d, _]) in input.iter().enumerate() {
115        for &[e, f, _, g, h, _] in &input[..index] {
116            // If the determinant is zero there is no solution possible
117            // which implies the trajectories are parallel.
118            let determinant = d * g - c * h;
119            if determinant == 0 {
120                continue;
121            }
122
123            // Invert the 2x2 matrix then multiply by the respective columns to find the times.
124            let t = (g * (f - b) - h * (e - a)) / determinant;
125            let u = (c * (f - b) - d * (e - a)) / determinant;
126
127            // We can pick either the first or second hailstone to find the intersection position.
128            let x = a + t * c;
129            let y = b + t * d;
130
131            // Both times must be in the future and the position within the specified area.
132            if t >= 0 && u >= 0 && RANGE.contains(&x) && RANGE.contains(&y) {
133                result += 1;
134            }
135        }
136    }
137
138    result
139}
140
141pub fn part2(input: &[[i64; 6]]) -> i128 {
142    // Calculations need the range of `i128`.
143    let widen = |i: usize| {
144        let [x, y, z, dx, dy, dz] = input[i].map(|n| n as i128);
145        (Vector { x, y, z }, Vector { x: dx, y: dy, z: dz })
146    };
147
148    // Take 3 arbitrary hailstones.
149    let (p0, v0) = widen(0);
150    let (p1, v1) = widen(1);
151    let (p2, v2) = widen(2);
152
153    // Subtract the positions and velocities to make them relative.
154    // The first hailstone is stationary at the origin.
155    let p3 = p1 - p0;
156    let p4 = p2 - p0;
157    let v3 = v1 - v0;
158    let v4 = v2 - v0;
159
160    // Find the normal to the plane that the second and third hailstones' velocities lie in.
161    // This is the cross product of their respective position and velocity.
162    // The cross product `s` of these two vectors is the same direction but not necessarily the
163    // same magnitude of the desired velocity of the rock.
164    // Only the direction is relevant (not the magnitude) so we can normalize the vector by the
165    // GCD of its components in order to prevent numeric overflow.
166    let q = v3.cross(p3).gcd();
167    let r = v4.cross(p4).gcd();
168    let s = q.cross(r).gcd();
169
170    // Find the times when the second and third hailstone intercept this vector.
171    // If the times are different then we can extrapolate the original position of the rock.
172    let t = (p3.y * s.x - p3.x * s.y) / (v3.x * s.y - v3.y * s.x);
173    let u = (p4.y * s.x - p4.x * s.y) / (v4.x * s.y - v4.y * s.x);
174    assert_ne!(t, u);
175
176    // Calculate the original position of the rock, remembering to add the first hailstone's
177    // position to convert back to absolute coordinates.
178    let a = (p0 + p3).sum();
179    let b = (p0 + p4).sum();
180    let c = (v3 - v4).sum();
181    (u * a - t * b + u * t * c) / (u - t)
182}