From 0a7aea65e1b89602b44fe2b5ee94dc92e96d0547 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 2 Jul 2023 23:13:08 +0200 Subject: [PATCH] day(23): introduce a helper function for DRY Signed-off-by: Matej Focko --- src/bin/day23.rs | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/src/bin/day23.rs b/src/bin/day23.rs index 98f3384..1464a3f 100644 --- a/src/bin/day23.rs +++ b/src/bin/day23.rs @@ -132,17 +132,20 @@ fn _show_ground_with_dimensions( } } +fn get_bounds(positions: &Input) -> (Vector2D, Vector2D) { + let f = |init, cmp: &dyn Fn(isize, isize) -> isize| { + positions + .iter() + .fold(Vector2D::new(init, init), |acc, elf| { + Vector2D::new(cmp(acc.x(), elf.x()), cmp(acc.y(), elf.y())) + }) + }; + + (f(isize::MAX, &min::), f(isize::MIN, &max::)) +} + fn _show_ground(positions: &Input) { - let min_pos = positions - .iter() - .fold(Vector2D::new(isize::MAX, isize::MAX), |acc, elf| { - Vector2D::new(min(acc.x(), elf.x()), min(acc.y(), elf.y())) - }); - let max_pos = positions - .iter() - .fold(Vector2D::new(isize::MIN, isize::MIN), |acc, elf| { - Vector2D::new(max(acc.x(), elf.x()), max(acc.y(), elf.y())) - }); + let (min_pos, max_pos) = get_bounds(positions); _show_ground_with_dimensions( positions, @@ -183,16 +186,7 @@ impl Solution for Day23 { // show_ground_with_dimensions(&positions, -3, 10, -2, 9); } - let min_pos = positions - .iter() - .fold(Vector2D::new(isize::MAX, isize::MAX), |acc, elf| { - Vector2D::new(min(acc.x(), elf.x()), min(acc.y(), elf.y())) - }); - let max_pos = positions - .iter() - .fold(Vector2D::new(isize::MIN, isize::MIN), |acc, elf| { - Vector2D::new(max(acc.x(), elf.x()), max(acc.y(), elf.y())) - }); + let (min_pos, max_pos) = get_bounds(&positions); (max_pos.x() - min_pos.x() + 1) * (max_pos.y() - min_pos.y() + 1) - (positions.len() as isize)