Skip to content

Instantly share code, notes, and snippets.

@sortega
Created September 10, 2019 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sortega/9227b3b3c02b0624f1f6aaf410ca64cd to your computer and use it in GitHub Desktop.
Save sortega/9227b3b3c02b0624f1f6aaf410ca64cd to your computer and use it in GitHub Desktop.
Coding exercise
package mentoring
object CodingExercise {
final case class Pos(x: Int, y: Int) {
def +(other: Pos) = Pos(x + other.x, y + other.y)
}
object Pos {
val Origin = Pos(0, 0)
}
val symbolToDelta = Map(
'<' -> Pos(0, -1),
'>' -> Pos(0, 1),
'^' -> Pos(1, 0),
'v' -> Pos(-1, 0)
)
def firstRepeatedPos(input: String): Option[Pos] = {
val positions = input.toStream.map(symbolToDelta).scanLeft(Pos.Origin)(_ + _)
val seenPositions = positions.scanLeft(Set.empty[Pos])(_ + _)
positions.zip(seenPositions).collectFirst {
case (position, seen) if seen.contains(position) => position
}
}
}
package mentoring
import mentoring.CodingExercise.Pos
import org.scalatest.{FlatSpec, Matchers}
final class CodingExerciseTest extends FlatSpec with Matchers {
"The first repeating position" should "not exist for the empty path" in {
CodingExercise.firstRepeatedPos("") shouldBe empty
}
it should "detect when it's crossed" in {
CodingExercise.firstRepeatedPos(">>^>v<") should ===(Some(Pos(0, 2)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment