Skip to content

Instantly share code, notes, and snippets.

@zsolt-donca
Created February 28, 2017 13:53
Show Gist options
  • Save zsolt-donca/6530610bbd6e5fa8dd16682692ce5b17 to your computer and use it in GitHub Desktop.
Save zsolt-donca/6530610bbd6e5fa8dd16682692ce5b17 to your computer and use it in GitHub Desktop.
val keypad: Seq[Seq[Int]] = Seq(Seq(1, 2, 3), Seq(4, 5, 6), Seq(7, 8, 9))
case class Pos(row: Int, col: Int)
sealed trait Dir
case object Up extends Dir
case object Left extends Dir
case object Right extends Dir
case object Down extends Dir
def move(pos: Pos, dir: Dir): Pos = (pos, dir) match {
case (Pos(0, _), Up) | (Pos(2, _), Down) |
(Pos(_, 0), Left) | (Pos(_, 2), Right) => pos
case (Pos(row, col), Up) => Pos(row - 1, col)
case (Pos(row, col), Down) => Pos(row + 1, col)
case (Pos(row, col), Left) => Pos(row, col - 1)
case (Pos(row, col), Right) => Pos(row, col + 1)
}
def walk(pos: Pos, dirs: Seq[Dir]): Pos = dirs.foldLeft(pos)(move)
def parseInstruction: Char => Dir = {
case 'U' => Up
case 'L' => Left
case 'R' => Right
case 'D' => Down
}
def parseInstructions(instructions: String): Seq[Seq[Dir]] = {
instructions.lines.map(_.map(parseInstruction)).toVector
}
def solve(instructions: String): Seq[Int] = {
val positions = parseInstructions(instructions).scanLeft(Pos(1, 1))(walk)
positions.tail.map(pos => keypad(pos.row)(pos.col))
}
val instructions =
"""|ULL
|RRDDD
|LURDL
|UUUUD"""
.stripMargin
solve(instructions)
@l0rinc
Copy link

l0rinc commented Mar 1, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment