From 1ed8961019c389053bda3492efa55c649b546eaf Mon Sep 17 00:00:00 2001 From: Kees van Kempen Date: Thu, 19 Dec 2024 13:45:32 +0100 Subject: [PATCH] 2024(5): halfly fix it, still need to only sum those that were updated --- 2024/5/puzzle1.py | 4 ++- 2024/5/puzzle2.py | 69 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 2024/5/puzzle2.py diff --git a/2024/5/puzzle1.py b/2024/5/puzzle1.py index 90c496a..4492493 100644 --- a/2024/5/puzzle1.py +++ b/2024/5/puzzle1.py @@ -31,7 +31,7 @@ def load_input(filename="input"): return rules, updates -def is_update_legal(update, rules) -> bool: +def is_update_legal(update, rules, print_offence=False) -> bool: for rule in rules: # Find indices of left hand side and right hand side lhs, rhs = rule @@ -41,6 +41,8 @@ def is_update_legal(update, rules) -> bool: # This reminds me of limes inferior and limes superior. # Thanks, Mueger. if max(indices(update, lhs)) > min(indices(update, rhs)): + if print_offence: + print(f"Rule", rule, "offended by update", update) return False return True diff --git a/2024/5/puzzle2.py b/2024/5/puzzle2.py new file mode 100644 index 0000000..3fb7a0c --- /dev/null +++ b/2024/5/puzzle2.py @@ -0,0 +1,69 @@ +from puzzle1 import * + + +verbose = True + +def swap(lst, idx_a, idx_b): + temp = lst[idx_a] + lst[idx_a] = lst[idx_b] + lst[idx_b] = temp + +def fix_update(update, rules): + """Fixes update according to rules by reference.""" + + # 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=" ") + + 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 + + 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") + +if __name__ == "__main__": + rules, updates = load_input() + + indices_legal = [] + middle_sum = 0 + # 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) + fix_update(update, rules) + updates[idx] = update + if is_update_legal(update, rules): + if verbose: + print(update, " is legal") + indices_legal.append(idx) + middle_sum += middle_page_num(update) + else: + if True or verbose: + print(update, " is illegal") + + if verbose: + print(indices_legal) + print(f"The sum of middle page numbers of legal updates is {middle_sum}.")