From 05f9ffa320b4651c24257be84b63b4f6f01fb047 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 7 Jan 2023 20:07:31 +0100 Subject: [PATCH] day(18): refactor a bit Signed-off-by: Matej Focko --- src/bin/day18.rs | 70 ++++++++++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/src/bin/day18.rs b/src/bin/day18.rs index 4924681..484dc54 100644 --- a/src/bin/day18.rs +++ b/src/bin/day18.rs @@ -20,26 +20,20 @@ lazy_static! { } fn get_bounding_box(droplets: &[Coord]) -> (Coord, Coord) { - let min_coord = + fn find(init: i32, comparator: &dyn Fn(i32, i32) -> i32, droplets: &[Coord]) -> Coord { droplets .iter() - .fold(Coord::new(i32::MAX, i32::MAX, i32::MAX), |acc, &droplet| { + .fold(Coord::new(init, init, init), |acc, &droplet| { Coord::new( - min(acc.x(), droplet.x()), - min(acc.y(), droplet.y()), - min(acc.z(), droplet.z()), + comparator(acc.x(), droplet.x()), + comparator(acc.y(), droplet.y()), + comparator(acc.z(), droplet.z()), ) - }); - let max_coord = - droplets - .iter() - .fold(Coord::new(i32::MIN, i32::MIN, i32::MIN), |acc, &droplet| { - Coord::new( - max(acc.x(), droplet.x()), - max(acc.y(), droplet.y()), - max(acc.z(), droplet.z()), - ) - }); + }) + } + + let min_coord = find(i32::MAX, &min, droplets); + let max_coord = find(i32::MIN, &max, droplets); (min_coord, max_coord) } @@ -63,6 +57,30 @@ enum Cube { Obsidian, } +fn construct_space(min_coords: Coord, max_coords: Coord) -> BTreeMap { + let mut space = BTreeMap::::new(); + + for cube in [ + min_coords.x()..=max_coords.x(), + min_coords.y()..=max_coords.y(), + min_coords.z()..=max_coords.z(), + ] + .into_iter() + .multi_cartesian_product() + .map(|coords| { + let (x, y, z) = coords + .into_iter() + .collect_tuple::<(i32, i32, i32)>() + .unwrap(); + + Coord::new(x, y, z) + }) { + space.insert(cube, Cube::Lava); + } + + space +} + fn aerate(space: &mut BTreeMap, start: Coord) { let mut queue = VecDeque::::new(); queue.push_back(start); @@ -116,29 +134,11 @@ impl Solution for Day18 { } fn part_2(input: &Input) -> Output { - let mut space = BTreeMap::::new(); - _check_bounding_box(input); // for debugging purposes let (min_coords, max_coords) = get_bounding_box(input); // lava everywhere - for cube in [ - min_coords.x()..=max_coords.x(), - min_coords.y()..=max_coords.y(), - min_coords.z()..=max_coords.z(), - ] - .into_iter() - .multi_cartesian_product() - .map(|coords| { - let (x, y, z) = coords - .into_iter() - .collect_tuple::<(i32, i32, i32)>() - .unwrap(); - - Coord::new(x, y, z) - }) { - space.insert(cube, Cube::Lava); - } + let mut space = construct_space(min_coords, max_coords); // override with obsidian for &droplet in input {