August 23, 2023

Solution for Advent of Code 2015 - Day 4: The Ideal Stocking Stuffer

 Link to the puzzle text

Part 1

For this puzzle, we mine some adventcoin by hashing data until the MD5 hash starts a certain number of  0s. The algorithm is straight forward: We start counting up from 0 and construct a string from our input and this number. This string is byte-encoded, hashed and checked for the correct number of 0s. Running both examples and my input took under a second, so further optimizations are not needed.

def mine_adventcoin(prefix, needed_zeroes):
for i in count(0):
string = prefix + str(i)
string = string.encode()
hash = hashlib.md5(string).hexdigest()
if hash[0:needed_zeroes] == "0" * needed_zeroes:
return i

Part 2

For part 2, we have the same task with a slightly higher number of 0s needed. Setting the argument needed_zeroes to 6 was enough to solve this problem with the function above.

Link to my solutions

No comments:

Post a Comment