Day 5: How About a Nice Game of Chess


In [1]:
with open("input/day5.txt", "r") as f:
    inputLines = [line for line in f]

doorId = bytes(inputLines[0].strip(), "utf-8")

In [2]:
import hashlib
import itertools

Implement a generator for 'interesting' hashes


In [3]:
def interestingHashes(prefix):
    for i in itertools.count():
        m = hashlib.md5()
        m.update(prefix + str(i).encode("utf-8"))
        h = m.hexdigest()
        if h.startswith("00000"):
            yield h

Part 1: Join the 5th character of each of the first 8 interesting hashes


In [4]:
def password1(prefix):
    return "".join(h[5] for h in itertools.islice(interestingHashes(prefix), 8))

In [5]:
password1(doorId)


Out[5]:
'1a3099aa'

Part 2: More complex password algorithm

  • If the 5th character of an interesting hash is a digit between 0 and 7, it tells us a position in the password.
  • This position is assigned to the 6th character of the interesting hash.
  • An interesting hash is ignored if the position given by its 5th character has been seen already.

In [6]:
def password2(prefix):
    result = [None] * 8
    for h in interestingHashes(prefix):
        if h[5] in "01234567":
            pos = int(h[5])
            if result[pos] is None:
                result[pos] = h[6]
                if all(c is not None for c in result):
                    return "".join(result)

In [7]:
password2(doorId)


Out[7]:
'694190cd'