From 17a0b665a50d5a5f72171da6f0f028f7c4a94f24 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Sun, 5 Dec 2021 11:51:59 +0100 Subject: [PATCH] 2021 day5/rust: avoid nightly for line point iterator --- 2021/day5/day5_rs/src/main.rs | 36 ++++++++++++----------------------- 1 file changed, 12 insertions(+), 24 deletions(-) diff --git a/2021/day5/day5_rs/src/main.rs b/2021/day5/day5_rs/src/main.rs index 63b52d0..c73d717 100644 --- a/2021/day5/day5_rs/src/main.rs +++ b/2021/day5/day5_rs/src/main.rs @@ -1,7 +1,5 @@ -#![feature(int_abs_diff)] #![warn(clippy::pedantic)] use std::{ - cmp::Ordering, convert::Infallible, io::{stdin, BufRead}, str::FromStr, @@ -40,25 +38,24 @@ impl FromStr for Line { } struct LinePoints { - pos: Vector2D, - x_change: Ordering, - y_change: Ordering, + pos: Vector2D, + step: Vector2D, points_left: usize, } impl LinePoints { fn new(line: &Line) -> Self { - let x_change = line.end.x.cmp(&line.start.x); - let y_change = line.end.y.cmp(&line.start.y); + let start = line.start.as_isizes(); + let end = line.end.as_isizes(); + let delta = end - start; + let step = Vector2D::new(delta.x.signum(), delta.y.signum()); - let delta_x = line.end.x.abs_diff(line.start.x); - let delta_y = line.end.y.abs_diff(line.start.y); + let len = usize::max(delta.x.unsigned_abs(), delta.y.unsigned_abs()); Self { - pos: line.start, - x_change, - y_change, - points_left: usize::max(delta_x, delta_y) + 1, + pos: start, + step, + points_left: len + 1, } } } @@ -72,18 +69,9 @@ impl Iterator for LinePoints { } let current = self.pos; - match self.x_change { - Ordering::Less => self.pos.x -= 1, - Ordering::Greater => self.pos.x += 1, - Ordering::Equal => {} - } - match self.y_change { - Ordering::Less => self.pos.y -= 1, - Ordering::Greater => self.pos.y += 1, - Ordering::Equal => {} - } + self.pos += self.step; self.points_left -= 1; - Some(current) + Some(current.as_usizes()) } }