Advertisement
Guest User

Untitled

a guest
May 5th, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. import scala.annotation.tailrec
  2.  
  3. object GraphDemo extends App {
  4. val graph = SimpleGraph(Nil)
  5. val from = SimpleNode(0, 0)
  6. val to = SimpleNode(15, 8)
  7. val moves = graph.shortestPath(from, to).getOrElse(Nil)
  8. moves.reverse.map(_.name).foreach(println)
  9. }
  10.  
  11. //CodinGame
  12. object Player extends App {
  13. val Array(startx, starty, exitx, exity) = for (i <- readLine split " ") yield i.trim.toInt
  14. val nbobstacles = readLine.trim.toInt // number of walls
  15. val obs = for (i <- 0 until nbobstacles) yield {
  16. val Array(posx, posy) = for (i <- readLine split " ") yield i.trim.toInt
  17. SimpleNode(posx, posy)
  18. }
  19.  
  20. val graph = SimpleGraph(obs.toList)
  21. val from = SimpleNode(startx, starty)
  22. val to = SimpleNode(exitx, exity)
  23. val moves = graph.shortestPath(from, to).getOrElse(Nil)
  24. println(moves.reverse.map(_.name).mkString(" "))
  25.  
  26. }
  27.  
  28. trait Graph {
  29. type Node
  30.  
  31. case class Move(from: Node, to: Node, name: String, cost: Double = 1)
  32.  
  33. type Path = List[Move]
  34.  
  35. def shortestPath(from: Node, to: Node): Option[Path] =
  36. pathImpl(to, List((from, Nil)), Nil)
  37.  
  38. def validMoves(from: Node): List[Move]
  39.  
  40. @tailrec
  41. private def pathImpl(
  42. to: Node,
  43. toExplore: List[(Node, Path)],
  44. explored: List[Node]): Option[Path] = toExplore match {
  45. case Nil => None
  46. case (`to`, path) :: _ => Some(path)
  47. case (node, path) :: t =>
  48. def alreadyQueued(n: Node) = toExplore.exists {
  49. case (`n`, _) => true
  50. case _ => false
  51. }
  52.  
  53. val newNodes = for {
  54. m <- validMoves(node)
  55. if !alreadyQueued(m.to)
  56. if !explored.contains(m.to)
  57. } yield (m.to, m :: path)
  58. pathImpl(to, t ::: newNodes, node :: explored)
  59. }
  60. }
  61.  
  62. case class SimpleNode(x: Int, y: Int) {
  63. override def toString = s"($x, $y)"
  64. }
  65.  
  66. case class SimpleGraph(impediments: List[SimpleNode], maxX: Int = 15, maxY: Int = 8, minX: Int = 0, minY: Int = 0) extends Graph {
  67. type Node = SimpleNode
  68.  
  69. def validMoves(n: SimpleNode): List[Move] = for {
  70. (dx, dy, name) <- List((0, 1, "DOWN"), (-1, 0, "LEFT"), (1, 0, "RIGHT"), (0, -1, "UP"))
  71. x = n.x + dx
  72. y = n.y + dy
  73. if (x >= minX && y >= minY && x <= maxX && y <= maxY)
  74. if (!impediments.contains(SimpleNode(x, y)))
  75. } yield Move(n, SimpleNode(x, y), name)
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement