54 lines
1.4 KiB
Python
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()
|