Skip to content

Instantly share code, notes, and snippets.

@stsatlantis
Last active December 5, 2015 08:51
Show Gist options
  • Save stsatlantis/6688b9e6d77a75c3f0d9 to your computer and use it in GitHub Desktop.
Save stsatlantis/6688b9e6d77a75c3f0d9 to your computer and use it in GitHub Desktop.
Advent of Code Day 4 solution in Scala || http://adventofcode.com/day/4
package hu.stsatlantis.fun.adventofcode2015
import java.security.MessageDigest
import scala.util.matching.Regex
/*
--- Day 4: The Ideal Stocking Stuffer ---
Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.
To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key
(your puzzle input, given below) followed by a number in decimal. To mine AdventCoins,
you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash.
For example:
If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...),
and it is the lowest such number to do so.
If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is,
the MD5 hash of pqrstuv1048970 looks like 000006136ef....
Your puzzle answer was 254575.
--- Part Two ---
Now find one that starts with six zeroes.
Your puzzle answer was 1038736.
*/
object Day4{
val part1 = """(00000.*)""".r
val part2 = """(000000.*)""".r
/*
* md5Hash
* Source: https://stevenwilliamalexander.wordpress.com/2012/06/11/scala-md5-hash-function-for-scala-console/
* */
def md5Hash(text: String): String = MessageDigest.getInstance("MD5").digest(text.getBytes).map {"%02x".format(_)}.foldLeft(""){_ + _}
def process(seed: String, pattern: Regex): Int = {
def calculate(str: String, count: Int): Int = {
md5Hash(str + count) match {
case pattern(_) => count
case _ => calculate(str, count + 1)
}
}
calculate(seed, 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment