2021 day5/rust: avoid nightly for line point iterator

This commit is contained in:
Xiretza 2021-12-05 11:51:59 +01:00
parent 5067c96550
commit 17a0b665a5

View file

@ -1,7 +1,5 @@
#![feature(int_abs_diff)]
#![warn(clippy::pedantic)] #![warn(clippy::pedantic)]
use std::{ use std::{
cmp::Ordering,
convert::Infallible, convert::Infallible,
io::{stdin, BufRead}, io::{stdin, BufRead},
str::FromStr, str::FromStr,
@ -40,25 +38,24 @@ impl FromStr for Line {
} }
struct LinePoints { struct LinePoints {
pos: Vector2D<usize>, pos: Vector2D<isize>,
x_change: Ordering, step: Vector2D<isize>,
y_change: Ordering,
points_left: usize, points_left: usize,
} }
impl LinePoints { impl LinePoints {
fn new(line: &Line) -> Self { fn new(line: &Line) -> Self {
let x_change = line.end.x.cmp(&line.start.x); let start = line.start.as_isizes();
let y_change = line.end.y.cmp(&line.start.y); 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 len = usize::max(delta.x.unsigned_abs(), delta.y.unsigned_abs());
let delta_y = line.end.y.abs_diff(line.start.y);
Self { Self {
pos: line.start, pos: start,
x_change, step,
y_change, points_left: len + 1,
points_left: usize::max(delta_x, delta_y) + 1,
} }
} }
} }
@ -72,18 +69,9 @@ impl Iterator for LinePoints {
} }
let current = self.pos; let current = self.pos;
match self.x_change { self.pos += self.step;
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.points_left -= 1; self.points_left -= 1;
Some(current) Some(current.as_usizes())
} }
} }