01020304050607080910111213141516171819202122232425

Advent of Code

2015/4

The Ideal Stocking Stuffer

in C#

by encse

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.

Read the full puzzle.

using System.Collections.Concurrent;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AdventOfCode.Y2015.Day04;

[ProblemName("The Ideal Stocking Stuffer")]
class Solution : Solver {

    public object PartOne(string input) => ParallelFind(input, "00000");
    public object PartTwo(string input) => ParallelFind(input, "000000");

    int ParallelFind(string input, string prefix) {
        var q = new ConcurrentQueue<int>();

        Parallel.ForEach(
            Numbers(), 
            () => MD5.Create(), 
            (i, state, md5) => {
                var hashBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(input + i));
                var hash = string.Join("", hashBytes.Select(b => b.ToString("x2")));

                if (hash.StartsWith(prefix)) {
                    q.Enqueue(i);
                    state.Stop();
                }
                return md5;
             }, 
             (_) => {}
        );
        return q.Min();
    }

    IEnumerable<int> Numbers() {
        for (int i=0; ;i++) {
            yield return i;
        }
    }
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator