Advent of Code - 2015
This is a solution to Day 4 of Advent of Code 2015.
Day 4 - The Ideal Stocking Stuffer
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.
For example:
- If your secret key is
abcdef
, the answer is609043
, because the MD5 hash ofabcdef609043
starts with five zeroes (000001dbbfa...
), and it is the lowest such number to do so.- If your secret key is
pqrstuv
, the lowest number it combines with to make an MD5 hash starting with five zeroes is1048970
; that is, the MD5 hash ofpqrstuv1048970
looks like000006136ef....
Read input
from utils import read_input
secret_key = read_input(4)[0]
Part 1
I'm doing a very naive solution here: start with 0 and try every number, creating the md5 hash (using built-in hashlib library's md5
function) and seeing if it starts with five zeroes.
import hashlib
def calculate_smallest_number(secret_key, zeroes=5):
number = 0
hexa = ''
while not hexa.startswith('0' * zeroes):
number += 1
hexa = hashlib.md5(f'{secret_key}{number}'.encode()).hexdigest()
return number
result = calculate_smallest_number(secret_key)
print(f'Solution: {result}')
assert result == 254575
Part 2
Now find one that starts with six zeroes.
When the change was this small, I was expecting the number to grow so much it would generate the naive solution too inefficient to run but it wasn't.
So I added an extra argument to the above function and called it with 6 to get the right answer.
result = calculate_smallest_number(secret_key, zeroes=6)
print(f'Solution: {result}')