71 lines
2.1 KiB
Python
71 lines
2.1 KiB
Python
import math
|
|
|
|
with open('updates.txt', 'r') as f:
|
|
updates = f.read().splitlines()
|
|
|
|
with open('rules.txt', 'r') as f:
|
|
rules = f.read().splitlines()
|
|
|
|
good_updates = []
|
|
corrected_updates = []
|
|
|
|
middle_page_count = 0
|
|
corrected_middle_page_count = 0
|
|
|
|
for update in updates:
|
|
good_update = False
|
|
for rule in rules:
|
|
num_a, num_b = rule.split('|')
|
|
if num_a in update and num_b in update:
|
|
if update.find(num_a) < update.find(num_b):
|
|
good_update = True
|
|
|
|
else:
|
|
good_update = False
|
|
break
|
|
|
|
if good_update:
|
|
good_updates.append(update)
|
|
|
|
else:
|
|
update_parse = list(map(int, update.split(',')))
|
|
corrected = False
|
|
|
|
while not corrected:
|
|
for rule in rules:
|
|
num_a, num_b = map(int, rule.split('|'))
|
|
if num_a in update_parse and num_b in update_parse:
|
|
if update_parse.index(num_a) > update_parse.index(num_b):
|
|
num_a, num_b = map(int, rule.split('|'))
|
|
|
|
num_a_index = update_parse.index(num_a)
|
|
num_b_index = update_parse.index(num_b)
|
|
|
|
update_parse.pop(num_b_index)
|
|
update_parse.insert(num_a_index, num_b)
|
|
|
|
for rule in rules:
|
|
num_a, num_b = map(int, rule.split('|'))
|
|
if num_a in update_parse and num_b in update_parse:
|
|
if update_parse.index(num_a) < update_parse.index(num_b):
|
|
corrected = True
|
|
|
|
else:
|
|
corrected = False
|
|
break
|
|
|
|
corrected_updates.append(update_parse)
|
|
print(update_parse)
|
|
|
|
for update in good_updates:
|
|
update_parse = list(map(int, update.split(',')))
|
|
middle_page_count += update_parse[math.floor(len(update_parse) / 2)]
|
|
|
|
for update in corrected_updates:
|
|
print(update)
|
|
print(update[math.floor(len(update) / 2)])
|
|
corrected_middle_page_count += update[math.floor(len(update) / 2)]
|
|
|
|
print(f'middle_page_count: {middle_page_count}')
|
|
print(f'corrected_middle_page_count: {corrected_middle_page_count}')
|