From e672c834265c15cd9c62c3cca85a72763341f718 Mon Sep 17 00:00:00 2001 From: Kees van Kempen Date: Thu, 19 Dec 2024 13:56:54 +0100 Subject: [PATCH] 2024(5): I hate this less --- 2024/5/puzzle2.py | 46 ++++++++++++++++------------------------------ 1 file changed, 16 insertions(+), 30 deletions(-) diff --git a/2024/5/puzzle2.py b/2024/5/puzzle2.py index 97c47d5..84f3915 100644 --- a/2024/5/puzzle2.py +++ b/2024/5/puzzle2.py @@ -1,7 +1,7 @@ from puzzle1 import * -verbose = True +verbose = False def swap(lst, idx_a, idx_b): temp = lst[idx_a] @@ -13,36 +13,21 @@ def fix_update(update, rules): # Allow the loop to be restared after a fix. i = 0 - update_free = True - while i < len(rules): - lhs, rhs = rules[i] - # NOTE: This is too verbose. - #if verbose: - # print(i, rules[i], end=" ") + swap_free = False + while not swap_free: + swap_free = True + for rule in rules: + lhs, rhs = rule - if not lhs in update or not rhs in update: - i += 1 - if i == len(rules) and not update_free: - i = 0 - update_free = True - # NOTE: This is a copied condition from below. - continue + if not lhs in update or not rhs in update: + continue - idx_lhs, idx_rhs = update.index(lhs), update.index(rhs) - if idx_lhs > idx_rhs: - if verbose: - print(f"swapping as {lhs} < {rhs}") - swap(update, idx_lhs, idx_rhs) - update_free = False - - i += 1 - if i == len(rules) and not update_free: - if verbose: - print("resetting") - i = 0 - update_free = True - elif i == len(rules): - print("stopping") + idx_lhs, idx_rhs = update.index(lhs), update.index(rhs) + if idx_lhs > idx_rhs: + if verbose: + print(f"swapping as {lhs} < {rhs}") + swap(update, idx_lhs, idx_rhs) + swap_free = False if __name__ == "__main__": rules, updates = load_input() @@ -51,7 +36,8 @@ if __name__ == "__main__": # Let's assume numbers can only occur once (although the checker does not # make this assumption), and every update CAN be fixed. for idx, update in enumerate(updates): - print(f"{idx:5d}/{len(updates)}:", update) + if verbose: + print(f"{idx:5d}/{len(updates)}:", update) if is_update_legal(update, rules): if verbose: print(update, " is legal")