more functional and elegant

This commit is contained in:
OMGOMG 2021-12-08 20:31:56 +01:00
parent e8339907fe
commit ecd2b002fa
1 changed files with 27 additions and 35 deletions

View File

@ -1,44 +1,36 @@
#!/usr/bin/env python3
from useful import *
used = 'abcefg cf acdeg acdfg bcdf abdfg abdefg acf abcdefg abcdfg'.split()
segment = 'ABCEFG CF ACDEG ACDFG BCDF ABDFG ABDEFG ACF ABCDEFG ABCDFG'.split()
maps = [dict(zip('abcdefg', perm)) for perm in permutations('ABCDEFG')]
perm = [list(zip('abcdefg', perm)) for perm in permutations('abcdefg')]
maps = [{p[0]: p[1] for p in pairs} for pairs in perm]
def parseline(s):
return [x.split() for x in s.split(' | ')]
ic(len(maps))
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 tpl(s):
a, b = s.split(' | ')
return a.split(), b.split()
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:
lines = [tpl(s) for s in lines(f)]
total = 0
for read, write in lines:
mapsleft = maps
for i in [1, 4, 7, 8]:
for sure in [r for r in read if len(r) == len(used[i])]:
mapsleft = [m for m in mapsleft if any(
all(m[s[j]] == used[i][j] for j in range(len(used[i]))) for s in permutations(sure)
)]
break
for dlen in 5, 6:
for notsure in [r for r in read if len(r) == dlen]:
mapsleft = [m for m in mapsleft if any(
any(
all(m[ns[j]] == u[j] for j in range(dlen)) for ns in permutations(notsure))
for u in filter(lambda x: len(x) == dlen, used))]
if(len(mapsleft) == 1):
break
n = 0
for digit in write:
ic(digit)
fixed = ''.join(sorted(mapsleft[0][c] for c in digit))
ic(fixed)
n *= 10
n += used.index(fixed)
total += n
print(total)
print(sum(get_output_value(*parseline(l)) for l in lines(f)))