Optimized solution
This commit is contained in:
@@ -18,21 +18,30 @@
|
|||||||
# an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of
|
# an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of
|
||||||
# pqrstuv1048970 looks like 000006136ef....
|
# pqrstuv1048970 looks like 000006136ef....
|
||||||
|
|
||||||
# Your puzzle input is yzbqklnj.
|
|
||||||
|
|
||||||
from hashlib import md5
|
from hashlib import md5
|
||||||
|
from itertools import count
|
||||||
|
|
||||||
_input = "yzbqklnj"
|
with open("files/P4.txt") as f:
|
||||||
|
secret_key = f.read().strip()
|
||||||
|
|
||||||
|
key_bytes = secret_key.encode()
|
||||||
|
|
||||||
|
|
||||||
def part_1() -> None:
|
def part_1() -> None:
|
||||||
end = "9" * len(_input)
|
padding = 5
|
||||||
for num in range(int(end)):
|
prefix = "0" * padding
|
||||||
testing = _input + str(num)
|
base_hash = md5(key_bytes)
|
||||||
result = md5(testing.encode()).hexdigest()
|
|
||||||
if result.startswith("0" * 5):
|
for num in count(1):
|
||||||
print(f"The lowest positive number is {num}")
|
digest_ctx = base_hash.copy()
|
||||||
break
|
digest_ctx.update(str(num).encode())
|
||||||
|
digest = digest_ctx.hexdigest()
|
||||||
|
if digest.startswith(prefix):
|
||||||
|
print(f"The lowest positive number starting with {padding} zeroes is {num}")
|
||||||
|
return
|
||||||
|
|
||||||
|
raise RuntimeError("No valid number found")
|
||||||
|
|
||||||
|
|
||||||
# --- Part Two ---
|
# --- Part Two ---
|
||||||
@@ -41,13 +50,19 @@ def part_1() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def part_2() -> None:
|
def part_2() -> None:
|
||||||
end = "9" * len(_input)
|
padding = 6
|
||||||
for num in range(int(end)):
|
prefix = "0" * padding
|
||||||
testing = _input + str(num)
|
base_hash = md5(key_bytes)
|
||||||
result = md5(testing.encode()).hexdigest()
|
|
||||||
if result.startswith("0" * 6):
|
for num in count(1):
|
||||||
print(f"The lowest positive number is {num}")
|
digest_ctx = base_hash.copy()
|
||||||
break
|
digest_ctx.update(str(num).encode())
|
||||||
|
digest = digest_ctx.hexdigest()
|
||||||
|
if digest.startswith(prefix):
|
||||||
|
print(f"The lowest positive number starting with {padding} zeroes is {num}")
|
||||||
|
return
|
||||||
|
|
||||||
|
raise RuntimeError("No valid number found")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user