From db747ef3fe5ba093971c6070c1aa104a8ba2c42c Mon Sep 17 00:00:00 2001 From: Baipyrus Date: Thu, 25 Jan 2024 17:48:12 +0100 Subject: [PATCH] calculate manhattan distance of pairs and sum --- src/day11/mod.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/day11/mod.rs b/src/day11/mod.rs index 30e5380..e8473f8 100644 --- a/src/day11/mod.rs +++ b/src/day11/mod.rs @@ -11,6 +11,22 @@ pub fn part_one() { let mut galaxies = extract(input); expand(&mut galaxies); + let distances = sum_dist(galaxies); + + println!("The sum of all distances is: '{distances}'."); +} + +fn sum_dist(galaxies: Vec) -> usize { + let mut distances = 0; + + for (i, a) in galaxies.iter().enumerate() { + for b in galaxies.iter().skip(i) { + if b.compare(a) { continue; } + distances += a.distance(b); + } + } + + distances } fn extract(symbols: Vec>) -> Vec { @@ -36,6 +52,17 @@ struct Galaxy { y: usize, } +impl Galaxy { + fn distance(&self, other: &Galaxy) -> usize { + let dx = (other.x as isize - self.x as isize).abs(); + let dy = (other.y as isize - self.y as isize).abs(); + (dx + dy) as usize + } + + fn compare(&self, other: &Galaxy) -> bool { + self.x == other.x && self.y == other.y + } +} fn setup() -> Vec> { let name = "day11";