day 21, what's make part 1 elegant makes part 2 ugly

This commit is contained in:
setop 2022-12-21 21:54:04 +01:00
parent 861d166533
commit ec41730982
3 changed files with 80 additions and 0 deletions

9
d21/draw.awk Normal file
View File

@ -0,0 +1,9 @@
BEGIN { print "digraph G {"}
{ k = substr($1,1,length($1)-1) }
NF == 2 { print k, "[label=\"" $0 "\"];" }
NF == 4 {
print k, "[label=\"" k " " $3 "\"];"
print k, "->", $2, ";"
print k, "->", $4, ";"
}
END { print "}" }

28
d21/part1.py Normal file
View File

@ -0,0 +1,28 @@
import sys
N = dict() # numbers
E = dict() # expressions
for l in sys.stdin.read().splitlines():
k, v = l.split(":")
v = v.strip()
if v.isdigit():
N[k]=int(v)
else:
w = v.split(" ")
E[k]=w
O = {
'*': lambda x,y: x*y,
'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
'/': lambda x,y: x/y,
}
while len(E)>0:
D = dict()
for k,v in E.items():
(a,o,b) = v
if a in N and b in N:
N[k] = O[o](N[a],N[b])
else:
D[k] = v
E = D
print(N["root"])

43
d21/part2.py Normal file
View File

@ -0,0 +1,43 @@
import sys
N = dict() # numbers
E = list() # expressions
I = {"+":"-","-":"+","*":"/","/":"*"}
for l in sys.stdin.read().splitlines():
k, v = l.split(":")
v = v.strip()
if v.isdigit():
N[k]=int(v)
else:
(a,o,b) = v.split(" ")
E.append((k,a,o,b))
if o in {"+","*"}:
E.append((a,k,I[o],b))
E.append((b,k,I[o],a))
else:
E.append((a,k,I[o],b))
E.append((b,a,o,k))
if len(N)<100:
N["pppw"] = 150
else:
N["qmfl"] = 54426117311903
N["qdpj"] = 54426117311903
del N["humn"]
O = {
'/': lambda x,y: x/y,
'-': lambda x,y: x-y,
'+': lambda x,y: x+y,
'*': lambda x,y: x*y,
}
while len(E)>0:
D = list()
for (k,a,o,b) in E:
if a in N and b in N:
N[k] = O[o](N[a],N[b])
if k == "humn":
print(N[k])
D = {}
break
else:
D.append((k,a,o,b))
E = D