You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.1 KiB

# %%
import itertools
# %% Define functions
def read_file(path):
"""Read the example input file and return a tuple of rules and orderings"""
rules = list()
updates = list()
with open(path, "r") as f:
for line in f:
if "|" in line:
rules.append(line)
elif not line.isspace():
updates.append(line)
return rules, updates
def prepare_rules(rules):
"""Prepare the rules for use by the analysis algorithm"""
return set(rules)
def process_updates(updates, rules):
sum = 0
for update in updates:
# Brute force this because I started late
nums = [int(val) for val in update.split(",")]
correct = True
for (i, num1), (j, num2) in itertools.product(enumerate(nums), enumerate(nums)):
if i < j:
bad_rule = f"{num2}|{num1}\n"
if bad_rule in rules:
correct = False
break
if correct:
sum += nums[int(len(nums) / 2)]
return sum
def fix_bad_update(update, rules):
sum = 0
for update in updates:
# Brute force this because I started late and don't have time to design a better algorithm
nums = [int(val) for val in update.split(",")]
fix_count = 0
correct = False
while correct == False:
correct = True
for (i, num1), (j, num2) in itertools.product(
enumerate(nums), enumerate(nums)
):
if i < j:
bad_rule = f"{num2}|{num1}\n"
if bad_rule in rules:
correct = False
fix_count += 1
nums[i] = num2
nums[j] = num1
break
if fix_count > 0:
sum += nums[int(len(nums) / 2)]
return sum
# %% Execut
if __name__ == "__main__":
rules, updates = read_file("./input.txt")
rules = prepare_rules(rules)
sum = process_updates(updates, rules)
print(f"Part1 answer is {sum}")
sum = fix_bad_update(updates, rules)
print(f"Part2 answer is {sum}")
# %%