This repository has been archived on 2024-12-22. You can view files and clone it, but cannot push or open issues or pull requests.
aoc2023/d9.py
felixm 9485fbae1d Solve day 9 and fix horrible bug in lib.
My integer parser did not consider negative values. I have fixed that
in the 2022 repository, but not here. That's pretty annoying.
2023-12-09 11:48:39 -05:00

54 lines
1.4 KiB
Python

import lib
EXAMPLE = """
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
"""
def solve(lines: list[str]):
res = 0
for (i, line) in enumerate(lines):
digits = lib.str_to_int_list(line)
last_digits = []
while not all(d == 0 for d in digits):
last_digits.append(digits[-1])
digits = [digits[i + 1] - digits[i] for i in range(len(digits) - 1)]
s = 0
for d in reversed(last_digits):
s = s + d
res += s
# 50:00 ... problem in my helper function... lol
return res
def solve2(lines: list[str]):
res = 0
for (i, line) in enumerate(lines):
digits = lib.str_to_int_list(line)
first_digits = []
while not all(d == 0 for d in digits):
first_digits.append(digits[0])
digits = [digits[i + 1] - digits[i] for i in range(len(digits) - 1)]
s = 0
for d in reversed(first_digits):
s = d - s
res += s
# 57:00...
return res
def main():
lines = lib.str_to_lines_no_empty(EXAMPLE)
print("Example 1:", solve(lines))
lines = lib.str_to_lines_no_empty(open("i9.txt").read())
print("Solution 1:", solve(lines))
lines = lib.str_to_lines_no_empty(EXAMPLE)
print("Example 2:", solve2(lines))
lines = lib.str_to_lines_no_empty(open("i9.txt").read())
print("Solution 2:", solve2(lines))
if __name__ == "__main__":
main()