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.
This commit is contained in:
felixm 2023-12-09 11:48:39 -05:00
parent 203f921c9f
commit 9485fbae1d
3 changed files with 57 additions and 3 deletions

View File

@ -7,4 +7,5 @@
- Day 5: 1st 25:00, 2nd 1:55:00; Required patience and accuracy
- Day 6: 13:54; I was slow because I thought it is much harder?
- Day 7: 75:00; leaderboard 16:00... that was just bad; no excuse
- Day 8:
- Day 8: 57:00; my input parse function did not consider negative values...
- Day 9:

53
d9.py Normal file
View File

@ -0,0 +1,53 @@
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()

4
lib.py
View File

@ -34,13 +34,13 @@ def lcm(numbers: list[int]) -> int:
def str_to_single_int(line: str) -> int:
line = line.replace(" ", "")
r = re.compile(r"\d+")
r = re.compile(r"-?\d+")
for m in r.findall(line):
return int(m)
raise Exception("No single digit sequence in '{line}'")
def str_to_int_list(line: str) -> list[int]:
r = re.compile(r"\d+")
r = re.compile(r"-?\d+")
return list(map(int, r.findall(line)))
def str_to_lines_no_empty(text: str) -> list[str]: