Created
December 8, 2021 08:27
-
-
Save pil0u/c001ff1e390aaf62653ff137c68ca41f to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Always sort letters (= positions) alphabetically for comparison | |
def sort_(s): | |
return "".join(sorted(s)) | |
part_1 = 0 | |
for seg in input_: | |
signals = seg.split(' | ')[1].split(' ') | |
for signal in signals: | |
if len(signal) in [2, 3, 4, 7]: | |
part_1 += 1 | |
part_2 = 0 | |
for seg in input_: | |
signals_output = seg.split(' | ') | |
signals = signals_output[0].split(' ') | |
output = [sort_(signal) for signal in signals_output[1].split(' ')] | |
translator = { | |
1: [sort_(s) for s in signals if len(s) == 2][0], | |
4: [sort_(s) for s in signals if len(s) == 4][0], | |
7: [sort_(s) for s in signals if len(s) == 3][0], | |
8: [sort_(s) for s in signals if len(s) == 7][0] | |
} | |
# Positions c and f are common to digits 1 and 7 | |
c_f = list(set(translator[7]) & set(translator[1])) | |
# Positions b and d are the only present in digit 4 but not in digit 7 | |
b_d = list(set(translator[4]) - set(translator[7])) | |
# Digit 3 is the only one with 5 segments and contains positions c and f | |
translator[3] = [sort_(s) for s in signals if len(s) == 5 and c_f[0] in s and c_f[1] in s][0] | |
# Digit 5 is the only one with 5 segments and contains positions b and d | |
translator[5] = [sort_(s) for s in signals if len(s) == 5 and b_d[0] in s and b_d[1] in s][0] | |
# Digit 2 is the remaining digit with 5 segments | |
translator[2] = [sort_(s) for s in signals if len(s) == 5 and sort_(s) not in [translator[3], translator[5]]][0] | |
# Digit 0 is the only one with 6 segments that does not contain _both_ positions b and d | |
translator[0] = [sort_(s) for s in signals if len(s) == 6 and (b_d[0] not in s or b_d[1] not in s)][0] | |
# Digit 6 is the only one with 6 segments that does not contain _both_ positions c and f | |
translator[6] = [sort_(s) for s in signals if len(s) == 6 and (c_f[0] not in s or c_f[1] not in s)][0] | |
# Digit 9 is the remaining digit with 6 segments | |
translator[9] = [sort_(s) for s in signals if len(s) == 6 and sort_(s) not in [translator[0], translator[6]]][0] | |
# Revert the dictionnary to easily access values | |
inv_translator = {v: str(k) for k, v in translator.items()} | |
# Convert the last 4 signals into an integer and sum it | |
part_2 += int("".join([inv_translator[s] for s in output])) | |
print(part_1) | |
print(part_2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment