Skip to content

Instantly share code, notes, and snippets.

@pakaufmann
Created December 5, 2016 08:48
Show Gist options
  • Save pakaufmann/750a13ca9d37ab12e378e2bc1d8c5e2d to your computer and use it in GitHub Desktop.
Save pakaufmann/750a13ca9d37ab12e378e2bc1d8c5e2d to your computer and use it in GitHub Desktop.
object Day5 extends Challenge {
val doorId = "abbhdwsy"
override def runFirst(): Unit = {
val password = hashes().filter(_.startsWith("00000")).take(8).map(_.charAt(5)).mkString
println(password)
}
def hashes(): Iterator[String] = {
Iterator.iterate(("", 0)) {
case (hash, index) =>
val toHash = doorId + index
val hexString = MessageDigest.getInstance("MD5").digest(toHash.getBytes).take(6).map("%02X" format _).mkString
(hexString, index + 1)
}.map(_._1)
}
override def runSecond(): Unit = {
val password = hashes()
.filter(_.startsWith("00000"))
.scanLeft(Array.fill[Option[Char]](8)(None)) {
case (pw, validHash) =>
try {
val pos = validHash(5).asDigit
if (pos < pw.length && pw(pos).isEmpty) {
pw(pos) = Some(validHash(6))
}
pw
} catch {
case e: NumberFormatException =>
//ignore
pw
}
}.dropWhile(_.exists(_.isEmpty)).map(_.flatten)
println(password.take(1).toList.map(_.mkString).head)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment