Created
February 28, 2017 13:53
-
-
Save zsolt-donca/6530610bbd6e5fa8dd16682692ce5b17 to your computer and use it in GitHub Desktop.
This file contains 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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative solution in
Kotlin
: https://gist.github.com/paplorinc/0d1942f07788a6b3782b5338d30aa367