lluque

AoC day 17

Dec 21st, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.60 KB | None | 0 0
  1. import java.security.MessageDigest
  2.  
  3. import scala.collection.mutable
  4.  
  5. object day17 extends App {
  6.  
  7.   def digest = MessageDigest.getInstance("MD5")
  8.   def seed: String = "vkjiggvb"
  9.   def dir: Map[Char, Int] = Map[Char, Int]('U' -> 0, 'D' -> 1, 'L' -> 2, 'R' -> 3)
  10.  
  11.   def md5(s: String): String = {
  12.     digest.digest(s.getBytes).map("%02x".format(_)).mkString
  13.   }
  14.  
  15.   case class Point(x: Int, y: Int) {
  16.     def withinBoundaries: Boolean = x > -1 && x < 4 && y > -1 && y < 4
  17.     def +(c: Char): Point = c match {
  18.       case 'U' => Point(x, y - 1)
  19.       case 'L' => Point(x - 1, y)
  20.       case 'D' => Point(x, y + 1)
  21.       case 'R' => Point(x + 1, y)
  22.     }
  23.   }
  24.  
  25.   def nextPoints(p: Point, dirs: List[Char]): Set[(Point, Char)] = {
  26.     (dir.keys zip md5(seed + dirs.mkString) take 4)
  27.       .filter(d => d._2 > 'a').map(d => (p + d._1, d._1))
  28.       .filter(_._1.withinBoundaries).toSet
  29.   }
  30.  
  31.   def bfs(start: Point, goal: Point): List[List[Char]] = {
  32.     val routes = mutable.ListBuffer[List[Char]]()
  33.     val queue = mutable.Queue[(Point, List[Point], List[Char])]((start, List(start), Nil))
  34.     while (queue.nonEmpty) {
  35.       val (point, path, dirs) = queue.dequeue
  36.       val neighbors = nextPoints(point, dirs)
  37.       for (neighbor <- neighbors) {
  38.         val (nextPoint, dir) = neighbor
  39.         if (nextPoint == goal) routes += dirs :+ dir
  40.         else queue.enqueue((nextPoint, path :+ nextPoint, dirs :+ dir))
  41.       }
  42.     }
  43.     routes.toList
  44.   }
  45.  
  46.   val (start, end) = (Point(0, 0), Point(3, 3))
  47.   val paths = bfs(start, end)
  48.   paths.minBy(p => p.length).mkString
  49.   paths.maxBy(p => p.length).length
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment