lluque

AoC day 4

Dec 28th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.18 KB | None | 0 0
  1. import scala.io.Source
  2.  
  3. object day4 extends App {
  4.  
  5.   def checksum(s: String) = s.reverse.slice(1, 6).reverse
  6.   def sectorId(s: String): Int = s.reverse.slice(7, 10).reverse.toInt
  7.   def name(s: String) = (s take s.length - 11) filterNot (_ == '-')
  8.   def occurrences(s: String): List[Char] = s.groupBy(identity)
  9.     .map(x => (x._1, x._2.length)).toList
  10.     .sortWith((a, b) => if (a._2 == b._2) a._1 < b._1 else a._2 > b._2) map (_._1)
  11.   def generateChecksum(s: String): String = {
  12.     (occurrences(name(s)) take 5).mkString
  13.   }
  14.   def isValid(s: String): Boolean = checksum(s) == generateChecksum(s)
  15.  
  16.   def decrypt(name: String, sectorId: Int): String = {
  17.     val alphabet = "abcdefghijklmnopqrstuvwxyz"
  18.     def rotateLeft(seq: Seq[Char], i: Int): Seq[Char] = {
  19.         val (first, last) = seq.splitAt(i % seq.size)
  20.         last ++ first
  21.     }
  22.     name.map(c => rotateLeft(alphabet, sectorId)(alphabet.indexOf(c)))
  23.   }
  24.  
  25.   val codes = Source.fromFile("day4.txt").getLines.toList
  26.   val sectorIds = codes filter isValid map sectorId
  27.   println(sectorIds.foldLeft(0)(_ + _))
  28.   val nr = codes.find(c => decrypt(name(c), sectorId(c)) startsWith("northpole"))
  29.   println(sectorId(nr.get))
  30.  
  31. }
Advertisement
Add Comment
Please, Sign In to add comment