#!/usr/bin/env python3 def is_valid_update(update, order_reqs): valid_update = True for i in range(0, len(update)): if update[i] in order_reqs: for j in range(0, len(update)): if update[j] in order_reqs[update[i]] and j < i: valid_update = False return valid_update def fix_update(update, order_reqs): if is_valid_update(update, order_reqs): return update else: fixed_update = update for i in range(0, len(update)): if update[i] in order_reqs: for j in range(0, len(update)): if update[j] in order_reqs[update[i]] and j < i: fixed_update[i], fixed_update[j] = fixed_update[j], fixed_update[i] if is_valid_update(fixed_update, order_reqs): return fixed_update else: return fix_update(fixed_update, order_reqs) with open("./2024/inputs/day05.txt") as f: lines = [l.strip() for l in f.readlines()] order_reqs = {} updates = [] nums_ended = False for l in lines: if l == "": nums_ended = True continue if not nums_ended: before, after = [int(n) for n in l.split("|")] if before not in order_reqs: order_reqs[before] = [after] else: order_reqs[before].append(after) else: updates.append([int(n) for n in l.split(",")]) middle_total = 0 invalid_updates = [] for update in updates: if is_valid_update(update, order_reqs): middle_total += update[int((len(update) - 1) / 2)] else: invalid_updates.append(update) print(middle_total) middle_total_fixed = 0 for update in invalid_updates: fixed_update = fix_update(update, order_reqs) middle_total_fixed += fixed_update[int((len(fixed_update) - 1) / 2)] print(middle_total_fixed)