53 lines
1.3 KiB
Python
53 lines
1.3 KiB
Python
from pathlib import Path
|
|
|
|
filepath = Path("./data/5_example")
|
|
filepath = Path("./data/5_input")
|
|
|
|
with open(filepath) as filein:
|
|
rules_l = []
|
|
while True:
|
|
dataline = filein.readline().rstrip()
|
|
if dataline == '':
|
|
break
|
|
else:
|
|
rules_l.append([int(i) for i in dataline.split('|')])
|
|
data_rest = filein.readlines()
|
|
|
|
rules = {(a,b) for a,b in rules_l}
|
|
|
|
instructions = [[int(i) for i in line.rstrip().split(',')] for line in data_rest]
|
|
erroneous = []
|
|
sum = 0
|
|
for instruction in instructions:
|
|
for i in range(len(instruction)-1):
|
|
pages = tuple(instruction[i:i+2])
|
|
if pages not in rules:
|
|
erroneous.append(instruction)
|
|
break
|
|
else:
|
|
center = len(instruction)//2
|
|
sum += instruction[center]
|
|
|
|
print(sum)
|
|
|
|
sum = 0
|
|
def multiple_goes(l: list):
|
|
result = []
|
|
for i in range(len(l)):
|
|
safe = True
|
|
for i in range(len(l)-1):
|
|
pages = tuple(l[i:i+2])
|
|
if pages not in rules:
|
|
safe = False
|
|
l[i:i+2] = pages[::-1]
|
|
if safe:
|
|
break
|
|
return l
|
|
|
|
for instruction in erroneous:
|
|
multiple_goes(instruction)
|
|
# print(instruction)
|
|
center = len(instruction)//2
|
|
sum += instruction[center]
|
|
|
|
print(sum)
|