1use 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 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 for _ in 0..1000 {
96 candidates.iter_mut().for_each(Particle::tick);
97 }
98
99 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 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}