Last active
July 15, 2019 13:18
-
-
Save fancellu/5344805255100168918d94014822e0ef to your computer and use it in GitHub Desktop.
Robot Wharehouse
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
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
..X....... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
X......... | |
.........X | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
.......... | |
X......... |
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
import scala.util.Try | |
object Robots extends App{ | |
object Direction extends Enumeration{ | |
type Direction=Value | |
val N,E,S,W=Value | |
} | |
final val MAX_X=10 | |
final val MAX_Y=10 | |
case class Robot(x:Int, y: Int){ | |
def moveRobot(direction: Direction.Value): Robot={ | |
direction match { | |
case Direction.N if x<MAX_X-1 => copy(x=x+1) | |
case Direction.E if y<MAX_Y-1 => copy(y=y+1) | |
case Direction.S if x>0 => copy(x=x-1) | |
case Direction.W if y>0 => copy(y=y-1) | |
case _=>this | |
} | |
} | |
} | |
def renderGrid(robot: Robot): String={ | |
List.tabulate(MAX_X, MAX_Y){ (x,y)=> | |
if (robot.x==x && robot.y==y) 'X' else '.' | |
}.map(_.mkString("")).reverse.mkString("\n")+ | |
"\n" | |
} | |
def moveRobot(route: Seq[Direction.Value], robot: Robot): Robot={ | |
route.foldLeft(robot){ _.moveRobot(_) } | |
} | |
def moveRobot(route: String, robot: Robot): Robot={ | |
moveRobot(parseRoute(route), robot) | |
} | |
def parseRoute(route: String): Seq[Direction.Value] ={ | |
route.split(' ').flatMap(name=>Try{Direction.withName(name)}.toOption).toList | |
} | |
val endRobot1=moveRobot("N N N E E S XXX", Robot(0,0)) | |
println(renderGrid(endRobot1)) | |
val endRobot2=moveRobot("S S S W W W W", endRobot1) | |
println(renderGrid(endRobot2)) | |
val topRight=moveRobot("N E "*20, endRobot2) | |
println(renderGrid(topRight)) | |
val bottomLeft=moveRobot("S W "*20, topRight) | |
println(renderGrid(bottomLeft)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment