From b8c01cc245af3fd8e2f7cf8870101ac1e73fd170 Mon Sep 17 00:00:00 2001 From: Thibaud Date: Sun, 8 Dec 2024 22:32:36 +0100 Subject: [PATCH] 2024 day 5 part 2 --- 2024/day5/day5.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/2024/day5/day5.py b/2024/day5/day5.py index 284f27c..c20a42e 100644 --- a/2024/day5/day5.py +++ b/2024/day5/day5.py @@ -7,25 +7,39 @@ def check_update(upd, rules): if [a, b] not in rules: return False return True - +def fix_update(upd, rules): + while not check_update(upd, rules): + for i in range(len(upd)): + for j in range(i+1, len(upd)): + if [upd[j], upd[i]] in rules: + upd[j], upd[i] = upd[i], upd[j] def main(content): - order, updates = content.split("\n\n") - order = [x.split("|") for x in order.split("\n")] + rules, updates = content.split("\n\n") + rules = [x.split("|") for x in rules.split("\n")] updates = [x.split(",") for x in updates.rstrip().split("\n")] part1 = 0 + incorrect_updates = [] for update in updates: - if check_update(update, order): + if check_update(update, rules): middle = update[len(update)//2] part1 += int(middle) + else: + incorrect_updates.append(update) print("Part 1: ", part1) + part2 = 0 + for update in incorrect_updates: + fix_update(update, rules) + middle = update[len(update)//2] + part2 += int(middle) + print("Part 2: ", part2) + if __name__ == "__main__": import sys infile = sys.argv[1] if 1 < len(sys.argv) else "example.txt" with open(infile) as f: main(f.read()) -