aoc/year2017/
day20.rs

1//! # Particle Swarm
2//!
3//! ## Part One
4//!
5//! The particle that remains closest to the origin as time goes to infinity has the lowest
6//! acceleration, measured via its manhattan value. If more than one particle shares the same
7//! lowest acceleration then ties are broken by velocity then by position.
8//!
9//! ## Part Two
10//!
11//! The input is constructed so that all collisions happen within 40 ticks so a simple brute force
12//! solution is much faster than more elegant alternatives, for example solving the quadratic
13//! equation describing each particle's position.
14use crate::util::hash::*;
15use crate::util::iter::*;
16use crate::util::parse::*;
17
18#[derive(Copy, Clone, PartialEq, Eq, Hash)]
19struct Vector {
20    x: i32,
21    y: i32,
22    z: i32,
23}
24
25impl Vector {
26    #[inline]
27    fn new(cs: [i32; 3]) -> Self {
28        Vector { x: cs[0], y: cs[1], z: cs[2] }
29    }
30
31    #[inline]
32    fn manhattan(self) -> i32 {
33        self.x.abs() + self.y.abs() + self.z.abs()
34    }
35
36    #[inline]
37    fn tick(&mut self, other: Vector) {
38        self.x += other.x;
39        self.y += other.y;
40        self.z += other.z;
41    }
42}
43
44#[derive(Copy, Clone)]
45pub struct Particle {
46    id: usize,
47    position: Vector,
48    velocity: Vector,
49    acceleration: Vector,
50}
51
52impl Particle {
53    #[inline]
54    fn tick(&mut self) {
55        self.velocity.tick(self.acceleration);
56        self.position.tick(self.velocity);
57    }
58}
59
60pub fn parse(input: &str) -> Vec<Particle> {
61    input
62        .iter_signed()
63        .chunk::<3>()
64        .chunk::<3>()
65        .enumerate()
66        .map(|(id, cs)| Particle {
67            id,
68            position: Vector::new(cs[0]),
69            velocity: Vector::new(cs[1]),
70            acceleration: Vector::new(cs[2]),
71        })
72        .collect()
73}
74
75pub fn part1(input: &[Particle]) -> usize {
76    let mut candidates = Vec::new();
77    let mut min = i32::MAX;
78
79    // Find particles with the lowest acceleration.
80    for particle in input {
81        let next = particle.acceleration.manhattan();
82
83        if next < min {
84            candidates.clear();
85            min = next;
86        }
87        if next == min {
88            candidates.push(*particle);
89        }
90    }
91
92    // Ensure all acceleration, velocity and position vectors are "aligned", that is the
93    // sign of each component is the same, for example a particle with a negative x acceleration
94    // should also have a negative x velocity and negative x position.
95    for _ in 0..1000 {
96        candidates.iter_mut().for_each(Particle::tick);
97    }
98
99    // Tie break by velocity then by position.
100    candidates.sort_unstable_by(|a, b| {
101        let first = a.velocity.manhattan().cmp(&b.velocity.manhattan());
102        let second = a.position.manhattan().cmp(&b.position.manhattan());
103        first.then(second)
104    });
105
106    candidates[0].id
107}
108
109pub fn part2(input: &[Particle]) -> usize {
110    let mut particles = input.to_vec();
111    let mut collisions = FastMap::with_capacity(input.len());
112    let mut exists = vec![i64::MAX; input.len()];
113
114    for time in 1..40 {
115        for (i, particle) in particles.iter_mut().enumerate() {
116            // Only consider particles that haven't collided in a previous tick.
117            // Multiple particles can collide in the same tick.
118            if exists[i] >= time {
119                particle.tick();
120
121                if let Some(j) = collisions.insert(particle.position, i) {
122                    exists[i] = time;
123                    exists[j] = time;
124                }
125            }
126        }
127
128        collisions.clear();
129    }
130
131    exists.iter().filter(|&&t| t == i64::MAX).count()
132}