lluque

AoC day 1

Dec 28th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.63 KB | None | 0 0
  1. import scala.io.Source
  2. import scala.annotation.tailrec
  3.  
  4. object day1 extends App {
  5.  
  6.   def getRoute(xs: List[(Char, Int)]): List[(Int, Int)] = {
  7.  
  8.     def nextDir(dir: Char, turn: Char): Char = dir match {
  9.       case 'E' => if (turn == 'R') 'S' else 'N'
  10.       case 'N' => if (turn == 'R') 'E' else 'W'
  11.       case 'W' => if (turn == 'R') 'N' else 'S'
  12.       case 'S' => if (turn == 'R') 'W' else 'E'
  13.     }
  14.  
  15.     def updateCoords(dir: Char, n: Int, c: (Int, Int)): List[(Int, Int)] = dir match {
  16.       case 'E' => (1 to n).map(i => (c._1 + i, c._2)).toList
  17.       case 'N' => (1 to n).map(i => (c._1, c._2 + i)).toList
  18.       case 'W' => (1 to n).map(i => (c._1 - i, c._2)).toList
  19.       case 'S' => (1 to n).map(i => (c._1, c._2 - i)).toList
  20.     }
  21.  
  22.     @tailrec
  23.     def drive(xs: List[(Char, Int)], dir: Char, acc: List[(Int, Int)]): List[(Int, Int)] = xs match {
  24.       case Nil => acc
  25.       case h :: t => {
  26.         val newDir = nextDir(dir, h._1)
  27.         val newCoords = updateCoords(newDir, h._2, acc.last)
  28.         drive(t, newDir, acc ::: newCoords)
  29.       }
  30.     }
  31.     drive(xs, 'N', List((0,0)))
  32.   }
  33.  
  34.   def findRevisit(xs: List[(Int, Int)], acc: List[(Int, Int)]): (Int, Int) = xs match {
  35.     case h :: t => if (acc.count(_ == h) == 1) h else findRevisit(t, acc :+ h)
  36.   }
  37.  
  38.   val lines = Source.fromFile("day1.txt").mkString
  39.   val blocks = lines.trim.split(", ") map (b => (b.head, b.drop(1).toInt))
  40.   val route = getRoute(blocks.toList)
  41.    
  42.   println((math.abs(route.last._1) + math.abs(route.last._2)))
  43.   val revisitedFirst = findRevisit(route, Nil)
  44.   println((math.abs(revisitedFirst._1) + math.abs(revisitedFirst._2)))
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment