Skip to content

Instantly share code, notes, and snippets.

@ASRagab
Created March 6, 2017 02:21
Show Gist options
  • Save ASRagab/5c16bba18b88724e31b34ecf8048b94a to your computer and use it in GitHub Desktop.
Save ASRagab/5c16bba18b88724e31b34ecf8048b94a to your computer and use it in GitHub Desktop.
case class Duck(x: Int, y: Int, direction: String)
case class Pond(x: Int, y: Int)
object GoldenPond extends App {
def getInput: (Pond, Seq[(Duck, List[String])]) = {
val scanner = new java.util.Scanner(System.in)
val pond = scanner.nextLine.split(" ").toList.map(_.toInt).take(2) match {
case Nil => throw new Exception("Not enough coordinates for pond")
case List(a, b) => Pond(a, b)
}
(pond, (1 to 2).map { _ =>
val duck = scanner.nextLine.split(" ").take(3).toList match {
case l: List[_] if l.length < 3 => throw new Exception("Incomplete Duck")
case List(x: String, y: String, z: String) => Duck(x.toInt, y.toInt, z)
}
val directions = scanner.nextLine.split("").toList
(duck, directions)
})
}
def computePond(input: (Pond, Seq[(Duck, List[String])])): Unit = {
val (pond, ducksAndDirections) = input
def directionSM(current: String, rotation: String) = {
current match {
case "N" => if (rotation == "P") "W" else "E"
case "S" => if (rotation == "P") "E" else "W"
case "W" => if (rotation == "P") "S" else "N"
case "E" => if (rotation == "P") "N" else "S"
}
}
def applySingleDirection(d: Duck, dir: String): Duck = {
if(dir == "S" || dir == "P")
d.copy(direction = directionSM(d.direction, dir))
else if(dir == "F")
d.direction match {
case "N" => d.copy(y = Math.min(pond.y, d.y + 1))
case "S" => d.copy(y = Math.max(0, d.y - 1))
case "E" => d.copy(x = Math.min(pond.x, d.x + 1))
case "W" => d.copy(x = Math.max(0, d.x - 1))
}
else throw new Exception("Bad Direction")
}
def applyDirections(d: Duck, directions: List[String]): Duck = {
directions.foldLeft(d)((duck, direction) => applySingleDirection(duck, direction))
}
ducksAndDirections.foreach{ pair =>
println(applyDirections(pair._1, pair._2)
.productIterator
.mkString(" "))
}
}
computePond(getInput)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment