From daad18c6af28c2a944490c10bcff9cba7a031de8 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Fri, 9 Dec 2022 21:36:05 +0100 Subject: [PATCH] 2022 day9/rust: abort early if knot doesn't move --- 2022/day9/rust/src/main.rs | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/2022/day9/rust/src/main.rs b/2022/day9/rust/src/main.rs index 5d4273d..4df0d05 100644 --- a/2022/day9/rust/src/main.rs +++ b/2022/day9/rust/src/main.rs @@ -1,3 +1,4 @@ +#![feature(iterator_try_reduce)] #![warn(clippy::pedantic)] use std::{ @@ -7,15 +8,14 @@ use std::{ use aoc::vec2::{Direction, Vec2}; -fn knot_movement(previous: Vec2, knot: Vec2) -> Vec2 { +fn knot_movement(previous: Vec2, knot: Vec2) -> Option { let (dx, dy) = (previous - knot).into(); - let movement = if dx.abs() <= 1 && dy.abs() <= 1 { - (0, 0) + if dx.abs() <= 1 && dy.abs() <= 1 { + None } else { - (dx.signum(), dy.signum()) - }; - movement.into() + Some((dx.signum(), dy.signum()).into()) + } } fn simulate_knots(num_knots: usize, instructions: &[(Direction, usize)]) -> usize { @@ -31,15 +31,12 @@ fn simulate_knots(num_knots: usize, instructions: &[(Direction, usize)]) -> usiz for _i in 0..*distance { knots[0] += Vec2::from(*direction); - let tail = knots - .iter_mut() - .reduce(|previous, knot| { - *knot += knot_movement(*previous, *knot); - knot - }) - .unwrap(); - - tail_positions.insert(*tail); + if let Some(tail) = knots.iter_mut().try_reduce(|previous, knot| { + *knot += knot_movement(*previous, *knot)?; + Some(knot) + }) { + tail_positions.insert(tail.copied().unwrap()); + } } }