0 Comments Posted in:

I’m still enjoying solving the Advent of Code daily challenges. Here’s a video of how I tackled day 4, with the code below

Solution in C#

var secretKey = "iwrupvqb"; //"pqrstuv"; //"abcdef";
var md5 = System.Security.Cryptography.MD5.Create();
var q = from n in Enumerable.Range(1, 10000000)
    let inputString = $"{secretKey}{n}"
    let inputBytes = System.Text.Encoding.ASCII.GetBytes(inputString)
    let hashBytes = md5.ComputeHash(inputBytes)
    let hashString = BitConverter.ToString(hashBytes).Replace("-","")
where hashString.StartsWith("00000") // a: five zeroes, b: six zeroes
select new { n, hashString };
q.FirstOrDefault().Dump();

Solution in F#

let secretKey = "iwrupvqb" //"pqrstuv"; //"abcdef";
let prefix = "00000"
let md5 = System.Security.Cryptography.MD5.Create()
let q = seq {
    for n in 1 .. 10000000 do
    let inputString = sprintf "%s%d" secretKey n
    let inputBytes = System.Text.Encoding.ASCII.GetBytes(inputString)
    let hashBytes = md5.ComputeHash(inputBytes)
    let hashString = BitConverter.ToString(hashBytes).Replace("-","")
    if hashString.StartsWith(prefix) then yield (n,hashString)
}
q |> Seq.head |> Dump
Want to learn more about LINQ? Be sure to check out my Pluralsight course More Effective LINQ. I'm also speaking on LINQ at Techorama Netherlands 2018 on 3rd October, so I'd love to see you there if you can make it.
Vote on HN