Advent of Code 2015 day 4 part2: solved

This commit is contained in:
Fabian Tessmer 2025-03-22 08:36:27 +01:00
parent eb6e8c2fec
commit 47d9ff38d4
3 changed files with 47 additions and 0 deletions

1
2015/day4/input.txt Normal file
View File

@ -0,0 +1 @@
yzbqklnj

17
2015/day4/problem.txt Normal file
View File

@ -0,0 +1,17 @@
--- 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 is 609043, because the MD5 hash of abcdef609043 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 is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....
Your puzzle answer was 282749.
--- Part Two ---
Now find one that starts with six zeroes.
Your puzzle answer was 9962624.
Both parts of this puzzle are complete! They provide two gold stars: **

29
2015/day4/solution.py Normal file
View File

@ -0,0 +1,29 @@
import hashlib
def get_first_md5_with_leading_zeroes(salt: str, num_zeros: int = 5) -> int:
pepper = 0
solution_found = False
leading_zeros = '0' * num_zeros
while not solution_found:
whole_string = salt + str(pepper)
if hashlib.md5(whole_string.encode()).hexdigest()[:num_zeros] == leading_zeros:
solution_found = True
pass
else:
pepper += 1
return pepper
if __name__ == "__main__":
assert get_first_md5_with_leading_zeroes("abcdef") == 609043, "Error: Example 1 couldn't be solved"
assert get_first_md5_with_leading_zeroes("pqrstuv") == 1048970, "Error: Example 2 couldn't be solved"
print("All tests passed")
puzzle_input = open("input.txt", "r").readline()
print("solution: ", get_first_md5_with_leading_zeroes(puzzle_input))
print("Part 2: ")
print("solution: ", get_first_md5_with_leading_zeroes(puzzle_input, 6))