diff --git a/src/bin/day11.rs b/src/bin/day11.rs index db30db3..efb48f4 100644 --- a/src/bin/day11.rs +++ b/src/bin/day11.rs @@ -12,6 +12,43 @@ struct Day11 { empty_ys: HashSet, empty_xs: HashSet, } + +impl Day11 { + fn solve(&self, factor: u64) -> u64 { + let to_add = factor - 1; + + (0..self.galaxies.len() - 1) + .map(|i| { + let (y0, x0) = self.galaxies[i]; + + (i + 1..self.galaxies.len()) + .map(|j| { + let (y1, x1) = self.galaxies[j]; + + let mut xd = x0.abs_diff(x1); + let mut yd = y0.abs_diff(y1); + + let (min_x, max_x) = if x0 <= x1 { (x0, x1) } else { (x1, x0) }; + for x in &self.empty_xs { + if (min_x as usize) < *x && *x < max_x as usize { + xd += to_add; + } + } + + for y in &self.empty_ys { + if (y0 as usize) < *y && *y < (y1 as usize) { + yd += to_add; + } + } + + xd + yd + }) + .sum::() + }) + .sum::() + } +} + impl Solution for Day11 { fn new>(pathname: P) -> Self { let lines: Vec = file_to_lines(pathname); @@ -42,67 +79,11 @@ impl Solution for Day11 { } fn part_1(&mut self) -> Output1 { - (0..self.galaxies.len() - 1) - .map(|i| { - let (y0, x0) = self.galaxies[i]; - - (i + 1..self.galaxies.len()) - .map(|j| { - let (y1, x1) = self.galaxies[j]; - - let mut xd = x0.abs_diff(x1); - let mut yd = y0.abs_diff(y1); - - let (min_x, max_x) = if x0 <= x1 { (x0, x1) } else { (x1, x0) }; - for x in &self.empty_xs { - if (min_x as usize) < *x && *x < max_x as usize { - xd += 1; - } - } - - for y in &self.empty_ys { - if (y0 as usize) < *y && *y < (y1 as usize) { - yd += 1; - } - } - - xd + yd - }) - .sum::() - }) - .sum::() + self.solve(2) } fn part_2(&mut self) -> Output2 { - (0..self.galaxies.len() - 1) - .map(|i| { - let (y0, x0) = self.galaxies[i]; - - (i + 1..self.galaxies.len()) - .map(|j| { - let (y1, x1) = self.galaxies[j]; - - let mut xd = x0.abs_diff(x1); - let mut yd = y0.abs_diff(y1); - - let (min_x, max_x) = if x0 <= x1 { (x0, x1) } else { (x1, x0) }; - for x in &self.empty_xs { - if (min_x as usize) < *x && *x < max_x as usize { - xd += 999999; - } - } - - for y in &self.empty_ys { - if (y0 as usize) < *y && *y < (y1 as usize) { - yd += 999999; - } - } - - xd + yd - }) - .sum::() - }) - .sum::() + self.solve(1000000) } } @@ -111,3 +92,22 @@ fn main() -> Result<()> { } test_sample!(day_11, Day11, 374, 82000210); + +#[cfg(test)] +mod day_11_extended { + use super::*; + + #[test] + fn solve_for_10() { + let path = Day11::get_sample(2); + let day = Day11::new(path); + assert_eq!(day.solve(10), 1030); + } + + #[test] + fn solve_for_100() { + let path = Day11::get_sample(2); + let day = Day11::new(path); + assert_eq!(day.solve(100), 8410); + } +}