diff --git a/src/main/scala/org/lemon/advent/lib/2d/Coord.scala b/src/main/scala/org/lemon/advent/lib/2d/Coord.scala index a624755..daa6539 100644 --- a/src/main/scala/org/lemon/advent/lib/2d/Coord.scala +++ b/src/main/scala/org/lemon/advent/lib/2d/Coord.scala @@ -67,4 +67,13 @@ case class Coord(x: Int, y: Int): def +(rhs: Coord): Coord = (x + rhs.x, y + rhs.y) def +(direction: Direction): Coord = move(direction) def -(rhs: Coord): Coord = (x - rhs.x, y - rhs.y) + def -(direction: Direction): Coord = move(direction.turnAround) def *(n: Int): Coord = (x * n, y * n) + + def directionTo(rhs: Coord): Option[Direction] = + val Coord(dx, dy) = rhs - this + if dx == 0 && dy < 0 then Some(Direction.Up) + else if dx == 0 && dy > 0 then Some(Direction.Down) + else if dx < 0 && dy == 0 then Some(Direction.Left) + else if dx > 0 && dy == 0 then Some(Direction.Right) + else None diff --git a/src/test/scala/org/lemon/advent/lib/2d/CoordTest.scala b/src/test/scala/org/lemon/advent/lib/2d/CoordTest.scala index 320ef2e..21e41f1 100644 --- a/src/test/scala/org/lemon/advent/lib/2d/CoordTest.scala +++ b/src/test/scala/org/lemon/advent/lib/2d/CoordTest.scala @@ -88,6 +88,34 @@ class CoordTest extends UnitTest: check((coord: Coord, n: Int) => coord.shift(Direction.Right, n) == coord.shiftRight(n)) } + test("left is left direction") { + check((coord: Coord) => coord.directionTo(coord.left) == Some(Direction.Left)) + } + + test("right is right direction") { + check((coord: Coord) => coord.directionTo(coord.right) == Some(Direction.Right)) + } + + test("up is up direction") { + check((coord: Coord) => coord.directionTo(coord.up) == Some(Direction.Up)) + } + + test("down is down direction") { + check((coord: Coord) => coord.directionTo(coord.down) == Some(Direction.Down)) + } + + test("direction to self is None") { + check((coord: Coord) => coord.directionTo(coord) == None) + } + + test("direction off line is None") { + check((coord: Coord, rhs: Coord) => + coord.x != rhs.x && coord.y != rhs.y ==> { + coord.directionTo(rhs) == None + } + ) + } + test("manhattan distance of adjacent is 1") { check((coord: Coord) => coord.adjacent.forall(_.manhattan(coord) == 1)) }