aoc2021/d08/d08_2.py

31 lines
1.1 KiB
Python
Raw Permalink Normal View History

2021-12-08 23:03:42 +00:00
import sys
S = 0
for l in sys.stdin.read().splitlines():
[code,num] = l.split('|')
codes = code.split(" ")
D = { }
# uniq choices 1,4,7,8
D[1] = [l for l in codes if len(l)==2][0]
D[7] = [l for l in codes if len(l)==3][0]
D[4] = [l for l in codes if len(l)==4][0]
D[8] = [l for l in codes if len(l)==7][0]
# multiple choices
L5 = [l for l in codes if len(l)==5] # 2 or 3 or 5
L6 = [l for l in codes if len(l)==6] # 0 or 6 or 9
# only 9 contains a 4 (and a 3)
D[9] = [l for l in L6 if (set(l)&set(D[4]))==set(D[4])][0]
# 0 contains a 7 and a 1 is not a 9
D[0] = [l for l in L6 if (set(l)&set(D[7]))==set(D[7]) and l != D[9]][0]
# 6 is not a 9 nor a 0
D[6] = [l for l in L6 if l != D[0] and l != D[9]][0]
# only 3 contains a 7
D[3] = [l for l in L5 if len(set(l)&set(D[7]))==3][0]
# 5 has only on difference with 6, 2 has 3
D[5] = [l for l in L5 if len(set(l)^set(D[6]))==1][0]
# 2 is not a 5 nor a 3
D[2] = [l for l in L5 if l != D[5] and l != D[3]][0]
# decode using inverted dictionary
E = {"".join(sorted(v)):k for (k,v) in D.items()}
S += int("".join(str(E["".join(sorted(i))]) for i in num.split(" ")[1:]))
print(S)