#!/usr/bin/env python # 2024 - Advent Of Code 5 - part 2 from math import floor # file = 'input_example.txt' file = 'input.txt' updates = [] rules = {} update = 0 with open(file, encoding="utf-8") as f: for line in f.read().splitlines(): if line == '': update = 1 continue if update == 0: before, after = line.split('|') if int(before) in rules: l = rules[int(before)] l.append(int(after)) rules[int(before)] = l else: rules[int(before)] = [int(after)] else: updates.append([int(x) for x in line.split(',')]) #print(f'{rules=}') #print(f'{updates=}') good_updates = [] bad_updates = [] for update in updates: broken_rule = False for num, page in enumerate(update): if page in rules: for p in rules[page]: if p in update[0:num]: broken_rule = True break if not broken_rule: good_updates.append(update) else: bad_updates.append(update) for update in bad_updates: working_update = update for num, page in enumerate(working_update): for u in working_update[:num]: if page in rules: if u in rules[page]: working_update.remove(u) working_update.insert(num, u) accum = 0 print(f'# bad_updates {len(good_updates)}') for u in bad_updates: accum += u[floor(len(u)/2)] print(f'{accum=}')