lluque

AoC day 14

Dec 18th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.38 KB | None | 0 0
  1. import java.security.MessageDigest
  2.  
  3. import scala.annotation.tailrec
  4. import scala.collection.mutable
  5.  
  6. object day14 {
  7.  
  8.   def salt: String = "cuanljph"
  9.   def match3 = "(.)\\1{2,}".r
  10.   def match5 = "(.)\\1{4,}".r
  11.   def digest = MessageDigest.getInstance("MD5")
  12.  
  13.   def md5(s: String, repeat: Int): String = {
  14.     def hash(h: String) =
  15.       digest.digest(h.getBytes).map("%02x".format(_)).mkString
  16.     (1 to repeat).par.foldLeft(s)((a, _) => hash(a))
  17.   }
  18.  
  19.   def findKeys(repeat: Int): List[Int] = {
  20.  
  21.     val triplets = mutable.Map[Char, List[Int]]().withDefaultValue(Nil)
  22.  
  23.     @tailrec
  24.     def inner(id: Int, acc: List[Int]): List[Int] = acc match {
  25.       case x if x.length >= 64 => acc
  26.       case x =>
  27.         val hash = md5(salt + id, repeat)
  28.         val quintuplet = match5.findFirstIn(hash)
  29.         if (quintuplet.isDefined) {
  30.           val matches = triplets(quintuplet.get.head).filter(_ + 1000 > id)
  31.           triplets(quintuplet.get.head) = List(id)
  32.           inner(id + 1, x ::: matches)
  33.         }
  34.         else {
  35.           val triplet = match3.findFirstIn(hash)
  36.           if (triplet.isDefined) {
  37.             triplets(triplet.get.head) = triplets(triplet.get.head) :+ id
  38.           }
  39.           inner(id + 1, x)
  40.         }
  41.     }
  42.     inner(0, Nil).sorted
  43.   }
  44.  
  45.   def run = {
  46.     println((findKeys(1) take 64).last)
  47.     println((findKeys(2017) take 64).last)
  48.   }
  49.  
  50. }
Advertisement
Add Comment
Please, Sign In to add comment