Skip to content

Advent of Code. Year 2015. Day 4

Published: (2 min read)

--- Day 4: The Ideal Stocking Stuffer ---

Today, we are going to mine some AdventCoins. For this, we need to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key followed by a number in decimal. We need to find the lowest number that produces such a hash.

Table of Contents

Open Table of Contents

Part 1

In order to get hash from the string we took a function from StackOverflow and slightly modified it.

private static string CreateMd5(string input)
{
  using (var md5 = MD5.Create())
  {
    var inputBytes = Encoding.ASCII.GetBytes(input);
    var hashBytes = md5.ComputeHash(inputBytes);
    var sb = new StringBuilder();
    foreach (var hashByte in hashBytes)
    {
      sb.Append(hashByte.ToString("X2"));
    }

    return sb.ToString();
  }
}

And then we used it to generate the new hash and when the hash starts with five zeros we return the number.

public string Part1(IEnumerable<string> input)
{
  var key = input.First();
  var number = 1;
  while (true)
  {
    var hash = CreateMd5($"{key}{number}");
    if (hash.StartsWith("00000"))
      break;

    number++;
  }
  return number.ToString();
}

Part 2

In the second part, we need to find the hash that starts at least with 6 zeroes. The resulting code is essentially the same except one line where we check hash for six zeroes.

public string Part2(IEnumerable<string> input)
{
  var key = input.First();
  var number = 1;
  while (true)
  {
    var hash = CreateMd5($"{key}{number}");
    if (hash.StartsWith("000000")) // 👈
      break;

    number++;
  }
  return number.ToString();
}

Links:

Other posts