Solution to problem 9 part 2 in Python
This commit is contained in:
parent
babefd4e12
commit
caf1e5ef7f
65
src/P9.py
65
src/P9.py
@ -1,3 +1,6 @@
|
||||
import sys
|
||||
from itertools import combinations
|
||||
|
||||
# --- Day 9: Encoding Error ---
|
||||
|
||||
# With your neighbor happily enjoying their video game, you turn your attention
|
||||
@ -73,24 +76,74 @@
|
||||
|
||||
|
||||
with open("files/P9.txt", "r") as f:
|
||||
numbers = [code for code in f.read().strip().split("\n")]
|
||||
|
||||
from itertools import combinations
|
||||
numbers = [int(num) for num in f.read().strip().split("\n")]
|
||||
|
||||
|
||||
def part_1() -> None:
|
||||
def part_1() -> int:
|
||||
window = 25
|
||||
for i in range(window, len(numbers)):
|
||||
if all(
|
||||
[
|
||||
int(x) + int(y) != int(numbers[i])
|
||||
x + y != numbers[i]
|
||||
for x, y in combinations(numbers[i - window : i], 2)
|
||||
]
|
||||
):
|
||||
break
|
||||
|
||||
print(f"The first number without the property is {numbers[i]}")
|
||||
return numbers[i]
|
||||
|
||||
|
||||
# --- Part Two ---
|
||||
|
||||
# The final step in breaking the XMAS encryption relies on the invalid number
|
||||
# you just found: you must find a contiguous set of at least two numbers in
|
||||
# your list which sum to the invalid number from step 1.
|
||||
|
||||
# Again consider the above example:
|
||||
|
||||
# 35
|
||||
# 20
|
||||
# 15
|
||||
# 25
|
||||
# 47
|
||||
# 40
|
||||
# 62
|
||||
# 55
|
||||
# 65
|
||||
# 95
|
||||
# 102
|
||||
# 117
|
||||
# 150
|
||||
# 182
|
||||
# 127
|
||||
# 219
|
||||
# 299
|
||||
# 277
|
||||
# 309
|
||||
# 576
|
||||
|
||||
# In this list, adding up all of the numbers from 15 through 40 produces the
|
||||
# invalid number from step 1, 127. (Of course, the contiguous set of numbers in
|
||||
# your actual list might be much longer.)
|
||||
|
||||
# To find the encryption weakness, add together the smallest and largest number
|
||||
# in this contiguous range; in this example, these are 15 and 47, producing 62.
|
||||
|
||||
# What is the encryption weakness in your XMAS-encrypted list of numbers?
|
||||
|
||||
|
||||
def part_2() -> None:
|
||||
target = invalid_number
|
||||
for i in range(len(numbers)):
|
||||
for j in range(i + 1, len(numbers)):
|
||||
if sum(numbers[i:j]) == target:
|
||||
print(
|
||||
f"The encryption weakness is {min(numbers[i:j]) + max(numbers[i:j])}"
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
part_1()
|
||||
invalid_number = part_1()
|
||||
part_2()
|
||||
|
Loading…
Reference in New Issue
Block a user