1
0
Fork 0

day(23): introduce a helper function for DRY

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2023-07-02 23:13:08 +02:00
parent ff519603f6
commit 0a7aea65e1
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -132,17 +132,20 @@ fn _show_ground_with_dimensions(
} }
} }
fn get_bounds(positions: &Input) -> (Vector2D<isize>, Vector2D<isize>) {
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::<isize>), f(isize::MIN, &max::<isize>))
}
fn _show_ground(positions: &Input) { fn _show_ground(positions: &Input) {
let min_pos = positions let (min_pos, max_pos) = get_bounds(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()))
});
_show_ground_with_dimensions( _show_ground_with_dimensions(
positions, positions,
@ -183,16 +186,7 @@ impl Solution<Input, Output> for Day23 {
// show_ground_with_dimensions(&positions, -3, 10, -2, 9); // show_ground_with_dimensions(&positions, -3, 10, -2, 9);
} }
let min_pos = positions let (min_pos, max_pos) = get_bounds(&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()))
});
(max_pos.x() - min_pos.x() + 1) * (max_pos.y() - min_pos.y() + 1) (max_pos.x() - min_pos.x() + 1) * (max_pos.y() - min_pos.y() + 1)
- (positions.len() as isize) - (positions.len() as isize)