2020 day 18

This commit is contained in:
felixm 2024-09-29 15:01:51 -04:00
parent 25443fba48
commit 695a4f7ddb
2 changed files with 108 additions and 1 deletions

106
2020/d18.py Normal file
View File

@ -0,0 +1,106 @@
from lib import get_data
def eval_1(s) -> int:
if type(s) is int:
return s
i = 0
parts = []
while i < len(s):
if s[i] == "(":
nested = 1
r = "("
i += 1
while nested > 0:
r += s[i]
if s[i] == ")":
nested -= 1
elif s[i] == "(":
nested += 1
i += 1
parts.append(r[1:-1])
elif s[i].isdigit():
d = ""
while i < len(s) and s[i].isdigit():
d += s[i]
i += 1
parts.append(int(d))
elif s[i] == " ":
pass
elif s[i] == "*" or s[i] == "+":
parts.append(s[i])
i += 1
i = 0
while len(parts) > 1:
if parts[1] == "*":
parts[2] = eval_1(parts[0]) * eval_1(parts[2])
parts = parts[2:]
elif parts[1] == "+":
parts[2] = eval_1(parts[0]) + eval_1(parts[2])
parts = parts[2:]
else:
assert False
return parts[-1]
def eval_2(s) -> int:
if type(s) is int:
return s
i = 0
parts = []
while i < len(s):
if s[i] == "(":
nested = 1
r = "("
i += 1
while nested > 0:
r += s[i]
if s[i] == ")":
nested -= 1
elif s[i] == "(":
nested += 1
i += 1
parts.append(r[1:-1])
elif s[i].isdigit():
d = ""
while i < len(s) and s[i].isdigit():
d += s[i]
i += 1
parts.append(int(d))
elif s[i] == " ":
pass
elif s[i] == "*" or s[i] == "+":
parts.append(s[i])
i += 1
while len(parts) > 1:
new_parts = []
for i in range(0, len(parts) - 1, 2):
if parts[i + 1] == "+":
new_parts.append(eval_2(parts[i]) + eval_2(parts[i + 2]))
new_parts += parts[i + 3 :]
break
elif parts[1] == "*":
new_parts.append(parts[i])
new_parts.append(parts[i + 1])
else:
assert False
else:
assert parts[1] == "*"
new_parts = [eval_2(parts[0]) * eval_2(parts[2])]
new_parts += parts[3:]
parts = new_parts
return parts[-1]
data = get_data(__file__)
t1, t2 = 0, 0
for line in data.splitlines():
t1 += eval_1(line)
t2 += eval_2(line)
print(t1)
print(t2)
assert t2 == 290726428573651

View File

@ -156,7 +156,8 @@ Solutions and utility script for Advent of Code challenges in Python.
- Day 15: 17:57 (Too slow for an easy one like this)
- Day 16: 33:00 (Not too unhappy really.)
- Day 17: 10:00 (40th)
- Day 18:
- Day 18: 80:00 (I am struggling with stuff where parsing is involved)
- Day 19:
## AoC 2022