instructions = []
updates = []
with open("input.txt") as file:
for line in file:
line = line.rstrip()
if line == "":
break
x, y = line.split('|')
instructions.append((int(x), int(y)))
for line in file:
line = line.rstrip()
pages = [int(i) for i in line.split(',')]
updates.append(pages)
def is_valid_update(update, instructions):
pos = {num: idx for idx, num in enumerate(update)}
for x, y in instructions:
if x in pos and y in pos and pos[x] > pos[y]:
return False
return True
valid_updates = [upd for upd in updates if is_valid_update(upd, instructions)]
accum_valid = sum(upd[len(upd) // 2] for upd in valid_updates)
print("Sum from valid updates:", accum_valid)
def domain_sort(update, instructions):
n = len(update)
for i in range(n):
for j in range(n):
if (update[j], update[i]) in instructions:
update[i], update[j] = update[j], update[i]
return update
invalid_updates = [upd for upd in updates if not is_valid_update(upd, instructions)]
sorted_updates = [domain_sort(upd.copy(), instructions) for upd in invalid_updates]
print("Sorted invalid updates:")
for upd in sorted_updates:
print(upd)
accum_sorted = sum(upd[len(upd) // 2] for upd in sorted_updates)
print("Sum from sorted invalid updates:", accum_sorted)
I would have a hard time understanding why this finishes with the "updates" in the order expected instead of the opposite order, and I'm intrigued. In the paper it just seems to counter-intuitive to me that if the comparison is that way round then the items get swapped ... if I found this in code I was auditing then I'd spent a long time trying to work out what was going on.
Yes, not something I would write in production code. But very easy for me to think about in a stream of consciousness. Usually I complete the above challenges in about 5-10mins.