From 9485fbae1dee52e252bfc6fcb19373b861b2f35a Mon Sep 17 00:00:00 2001 From: felixm Date: Sat, 9 Dec 2023 11:48:39 -0500 Subject: [PATCH] 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. --- README.md | 3 ++- d9.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ lib.py | 4 ++-- 3 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 d9.py diff --git a/README.md b/README.md index ad7887d..b239c3c 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/d9.py b/d9.py new file mode 100644 index 0000000..dadaebe --- /dev/null +++ b/d9.py @@ -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() diff --git a/lib.py b/lib.py index 2170f46..6373b11 100644 --- a/lib.py +++ b/lib.py @@ -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]: