completes day5

This commit is contained in:
JasterV 2021-12-10 19:02:31 +01:00
parent 63a56cd97e
commit 337bb31b7d

View file

@ -7,18 +7,41 @@ pub struct Line(Point, Point);
impl Line {
pub fn get_points(&self) -> Vec<Point> {
match self {
// Vertical lines
Line(Point(x1, y1), Point(x2, y2)) if x1 == x2 && y1 <= y2 => {
(*y1..=*y2).map(|y| Point(*x1, y)).collect()
}
Line(Point(x1, y1), Point(x2, y2)) if x1 == x2 && y2 <= y1 => {
(*y2..=*y1).map(|y| Point(*x1, y)).collect()
}
// Horizontal lines
Line(Point(x1, y1), Point(x2, y2)) if y1 == y2 && x1 <= x2 => {
(*x1..=*x2).map(|x| Point(x, *y1)).collect()
}
Line(Point(x1, y1), Point(x2, y2)) if y1 == y2 && x2 <= x1 => {
(*x2..=*x1).map(|x| Point(x, *y1)).collect()
}
// Diagonal lines
Line(Point(x1, y1), Point(x2, y2)) if y1 < y2 && x1 < x2 => (*x1..=*x2)
.zip(*y1..=*y2)
.map(|(x, y)| Point(x, y))
.collect(),
Line(Point(x1, y1), Point(x2, y2)) if y1 < y2 && x1 > x2 => (*x2..=*x1)
.rev()
.zip(*y1..=*y2)
.map(|(x, y)| Point(x, y))
.collect(),
Line(Point(x1, y1), Point(x2, y2)) if y1 > y2 && x1 > x2 => (*x2..=*x1)
.zip(*y2..=*y1)
.map(|(x, y)| Point(x, y))
.collect(),
Line(Point(x1, y1), Point(x2, y2)) if y1 > y2 && x1 < x2 => (*x1..=*x2)
.zip((*y2..=*y1).rev())
.map(|(x, y)| Point(x, y))
.collect(),
_ => vec![],
}
}
@ -36,3 +59,24 @@ impl From<String> for Line {
Line(Point(x1, y1), Point(x2, y2))
}
}
#[cfg(test)]
mod tests {
use super::{Line, Point};
#[test]
fn gets_diagonal_line_points() {
let line = Line(Point(5, 5), Point(8, 2));
let points = line.get_points();
assert_eq!(points, [Point(5, 5), Point(6, 4), Point(7, 3), Point(8, 2)])
}
#[test]
fn gets_diagonal_line_points2() {
let line = Line(Point(8, 2), Point(5, 5));
let points = line.get_points();
assert_eq!(points, [Point(8, 2), Point(7, 3), Point(6, 4), Point(5, 5)])
}
}