1
0
Fork 0

day(11): factor out the solution for any factor

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-12-11 10:41:44 +01:00
parent 95d451d103
commit 09e0d81ffe
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -12,6 +12,43 @@ struct Day11 {
empty_ys: HashSet<usize>,
empty_xs: HashSet<usize>,
}
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::<u64>()
})
.sum::<u64>()
}
}
impl Solution<Output1, Output2> for Day11 {
fn new<P: AsRef<Path>>(pathname: P) -> Self {
let lines: Vec<String> = file_to_lines(pathname);
@ -42,67 +79,11 @@ impl Solution<Output1, Output2> 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::<u64>()
})
.sum::<u64>()
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::<u64>()
})
.sum::<u64>()
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);
}
}