mirror of
https://codeberg.org/JasterV/aoc_2021.git
synced 2026-04-26 18:40:05 +00:00
completes day5
This commit is contained in:
parent
63a56cd97e
commit
337bb31b7d
1 changed files with 44 additions and 0 deletions
|
|
@ -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)])
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue