2022 day9/rust: abort early if knot doesn't move
This commit is contained in:
parent
e1862bdcbb
commit
daad18c6af
1 changed files with 12 additions and 15 deletions
|
@ -1,3 +1,4 @@
|
||||||
|
#![feature(iterator_try_reduce)]
|
||||||
#![warn(clippy::pedantic)]
|
#![warn(clippy::pedantic)]
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
|
@ -7,15 +8,14 @@ use std::{
|
||||||
|
|
||||||
use aoc::vec2::{Direction, Vec2};
|
use aoc::vec2::{Direction, Vec2};
|
||||||
|
|
||||||
fn knot_movement(previous: Vec2, knot: Vec2) -> Vec2 {
|
fn knot_movement(previous: Vec2, knot: Vec2) -> Option<Vec2> {
|
||||||
let (dx, dy) = (previous - knot).into();
|
let (dx, dy) = (previous - knot).into();
|
||||||
|
|
||||||
let movement = if dx.abs() <= 1 && dy.abs() <= 1 {
|
if dx.abs() <= 1 && dy.abs() <= 1 {
|
||||||
(0, 0)
|
None
|
||||||
} else {
|
} else {
|
||||||
(dx.signum(), dy.signum())
|
Some((dx.signum(), dy.signum()).into())
|
||||||
};
|
}
|
||||||
movement.into()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn simulate_knots(num_knots: usize, instructions: &[(Direction, usize)]) -> usize {
|
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 {
|
for _i in 0..*distance {
|
||||||
knots[0] += Vec2::from(*direction);
|
knots[0] += Vec2::from(*direction);
|
||||||
|
|
||||||
let tail = knots
|
if let Some(tail) = knots.iter_mut().try_reduce(|previous, knot| {
|
||||||
.iter_mut()
|
*knot += knot_movement(*previous, *knot)?;
|
||||||
.reduce(|previous, knot| {
|
Some(knot)
|
||||||
*knot += knot_movement(*previous, *knot);
|
}) {
|
||||||
knot
|
tail_positions.insert(tail.copied().unwrap());
|
||||||
})
|
}
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
tail_positions.insert(*tail);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue