aoc-2021/10_day/code.py

53 lines
1.1 KiB
Python
Raw Normal View History

2021-12-10 12:42:11 +00:00
import fileinput
2021-12-13 09:08:40 +00:00
scores = [3, 57, 1197, 25137]
2021-12-10 12:42:11 +00:00
opening_chars = ['(', '[', '{', '<']
closing_chars = [')', ']', '}', '>']
lines = fileinput.input()
score = []
completions = []
completion_points = []
for line in lines:
total = 0
stack = []
line = line.strip()
complete = True
for column, c in enumerate(line):
if c in opening_chars:
2021-12-13 09:08:40 +00:00
stack.append(opening_chars.index(c))
2021-12-10 12:42:11 +00:00
if c in closing_chars:
i = closing_chars.index(c)
2021-12-13 09:08:40 +00:00
if stack[-1] != i:
2021-12-10 12:42:11 +00:00
expected_i = opening_chars.index(stack[-1])
# print(line)
# print(''.join(column*[' ']+['^']))
# print(f'Expected {closing_chars[expected_i]} but found {c}')
# print('')
score.append(scores[i])
complete = False
break
stack.pop()
if not complete: continue
# the line is just incomplete
completion = []
while len(stack) > 0:
i = opening_chars.index(stack.pop())
char = closing_chars[i]
total = total*5 + (i+1)
completion.append(char)
completion_points.append(total)
print(''.join(completion))
completion_points.sort()
print('part 1')
print(score)
print(sum(score))
print('part 2')
print(completion_points)
print(completion_points[len(completion_points)//2])