52 lines
1.2 KiB
Python
52 lines
1.2 KiB
Python
from itertools import permutations
|
|
|
|
|
|
with open("input.txt") as f:
|
|
plines = [line.strip().split(" | ") for line in f.read().strip().split("\n")]
|
|
puzzles = [
|
|
(signals.split(), digits.split(), )
|
|
for signals, digits in plines
|
|
]
|
|
|
|
|
|
# get a list of valid abcd combinations under the "correct" mapping
|
|
valid_digits = ["abcefg", "cf", "acdeg", "acdfg", "bcdf", "abdfg", "abdefg", "acf", "abcdefg", "abcdfg"]
|
|
digits_s = set(valid_digits)
|
|
|
|
|
|
# create all possible mappings
|
|
mappings = []
|
|
for s in permutations("abcdefg"):
|
|
mappings.append({s: "abcdefg"[i] for i, s in enumerate(s)})
|
|
|
|
|
|
def apply_mapping(s, mapping):
|
|
nc = []
|
|
for c in s:
|
|
nc.append(mapping[c])
|
|
return ''.join(sorted(nc))
|
|
|
|
|
|
total = 0
|
|
|
|
for pn, (signals, digits) in enumerate(puzzles):
|
|
for mn, mapping in enumerate(mappings):
|
|
found = True
|
|
ok = 0
|
|
for num in signals:
|
|
localized = apply_mapping(num, mapping)
|
|
if localized not in digits_s:
|
|
found = False
|
|
break
|
|
ok += 1
|
|
|
|
if found:
|
|
mapped = [apply_mapping(d, mapping) for d in digits]
|
|
nums = [str(valid_digits.index(l)) for l in mapped]
|
|
total += int(''.join(nums))
|
|
|
|
|
|
print(total)
|
|
|
|
# 1h3m
|