Skip to content

Commit

Permalink
✨ add Coord#directionTo and -(Direction)
Browse files Browse the repository at this point in the history
  • Loading branch information
twentylemon committed Dec 6, 2024
1 parent bdfec83 commit 49a0149
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/main/scala/org/lemon/advent/lib/2d/Coord.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
28 changes: 28 additions & 0 deletions src/test/scala/org/lemon/advent/lib/2d/CoordTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down

0 comments on commit 49a0149

Please sign in to comment.