Created
September 10, 2019 08:03
-
-
Save sortega/9227b3b3c02b0624f1f6aaf410ca64cd to your computer and use it in GitHub Desktop.
Coding exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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