Solve 2021 day 7-11

This commit is contained in:
2024-11-21 08:43:15 -05:00
parent 11bcbce099
commit e9bd759dba
6 changed files with 244 additions and 7 deletions

63
2021/d10.py Normal file
View File

@@ -0,0 +1,63 @@
from lib import get_data
data = get_data(__file__).strip()
OPEN = "([{<"
CLOSE = ")]}>"
def part1(line):
score = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
stack = []
for c in line:
if c in OPEN:
stack.append(OPEN.index(c))
elif c in CLOSE:
ci = CLOSE.index(c)
if stack and stack[-1] == ci:
stack.pop()
continue
else:
return score[c]
else:
assert False
return 0
def part2(line):
stack = []
for c in line:
if c in OPEN:
stack.append(OPEN.index(c))
elif c in CLOSE:
ci = CLOSE.index(c)
if stack and stack[-1] == ci:
stack.pop()
continue
else:
assert False
else:
assert False
score = 0
for v in reversed(stack):
score *= 5
score += v + 1
return score
s1 = 0
s2s = []
for line in data.splitlines():
s = part1(line)
if s == 0:
s2s.append(part2(line))
s1 += s
print(s1)
s2 = sorted(s2s)[len(s2s) // 2]
print(s2)