advent2021/eight_second.py

37 lines
1.2 KiB
Python
Executable File

#!/usr/bin/env python3
from useful import *
segment = 'ABCEFG CF ACDEG ACDFG BCDF ABDFG ABDEFG ACF ABCDEFG ABCDFG'.split()
maps = [dict(zip('abcdefg', perm)) for perm in permutations('ABCDEFG')]
def parseline(s):
return [x.split() for x in s.split(' | ')]
def match_map(m, scrambled, clean):
return any(
all(m[s[j]] == clean[j] for j in range(len(clean)))
for s in permutations(scrambled))
def good_map(maps, pattern, digits):
if(len(maps) == 1):
return maps[0]
return good_map(
[m for m in maps if all(
any(
match_map(m, scrambled, s)
for s in filter(lambda x: len(x) == digits[0], segment))
for scrambled in filter(lambda r: len(r) == digits[0], pattern))],
pattern,
digits[1:])
def get_output_value(pattern, value):
mapping = good_map(maps, pattern, [2, 3, 4, 7, 5, 6])
return reduce(lambda acc, digit:
acc * 10 + segment.index(''.join(sorted(mapping[c] for c in digit))),
value,
0)
with open(0) as f:
print(sum(get_output_value(*parseline(l)) for l in lines(f)))