Advent of Code: Day 4

Source

Part 1: Mine Adventcoins. Basically, find the lowest integer such that the string {prefix}{integer} has an md5 hash with at least 5 leading zeros. 123

def naturals(i = 0):
    while True:
        yield i
        i += 1

def mine(prefix, length):
    for i in naturals(1):
        coin = '{prefix}{suffix}'.format(prefix = prefix, suffix = i).encode('utf-8')
        hash = hashlib.md5(coin).hexdigest()
        if all(c == '0' for c in hash[0:length]):
            return (i, hash)

print(mine(sys.argv[1], 5))

naturals is code that I’ve used on a number of previous occasions and basically stole borrowed from Racket’s n-naturals . It allows you to iterate indefinitely over the natural numbers. Then, just hash and look for enough leading zeros.

Part 2: Do the same thing, only with six leading zeros.

Nothing changes; just change the length parameter and wait a bit longer. Moderns computers can still crunch through a whole heck of a lot of hashes (9958218 for my particular input) in next to no time at all.


  1. This is actually roughly exactly how Bitcoin mining works. ↩︎

  2. I should post about that sometime. ↩︎

  3. Oh hey, I did ↩︎