83 lines
2.1 KiB
Python
83 lines
2.1 KiB
Python
displays = []
|
|
with open("input.txt") as f:
|
|
displays = [
|
|
[patterns, output]
|
|
for line in f.read().split('\n')
|
|
for patterns, output in [line.split(' | ')]
|
|
]
|
|
|
|
part1 = 0
|
|
for display in displays:
|
|
_, output = display
|
|
for signal in output.split(' '):
|
|
if len(signal) in [2, 4, 3, 7]: # "1", "4", "7", and "8" are unique
|
|
part1 += 1
|
|
print(part1)
|
|
|
|
part2 = 0
|
|
for display in displays:
|
|
patterns, output = display
|
|
patterns = patterns.split(' ')
|
|
output = output.split(' ')
|
|
# we're going to use set theory. some digits are ambigous...
|
|
ZERO_SIX_OR_NINE = set()
|
|
TWO_THREE_OR_FIVE = set()
|
|
# preliminary sorting based on known lengths
|
|
for pattern in patterns:
|
|
if len(pattern) == 2:
|
|
ONE = set(pattern)
|
|
elif len(pattern) == 4:
|
|
FOUR = set(pattern)
|
|
elif len(pattern) == 3:
|
|
SEVEN = set(pattern)
|
|
elif len(pattern) == 7:
|
|
EIGHT = set(pattern)
|
|
elif len(pattern) == 6:
|
|
ZERO_SIX_OR_NINE.add(pattern)
|
|
elif len(pattern) == 5:
|
|
TWO_THREE_OR_FIVE.add(pattern)
|
|
# do some set geometry to figure out the ambiguous digits
|
|
for pattern in ZERO_SIX_OR_NINE:
|
|
if (set(pattern) | ONE ) == EIGHT:
|
|
SIX = set(pattern)
|
|
ZERO_OR_NINE = {p for p in ZERO_SIX_OR_NINE if p != pattern}
|
|
R1 = EIGHT - SIX
|
|
R2 = ONE - R1
|
|
for pattern in TWO_THREE_OR_FIVE:
|
|
if ONE.issubset(set(pattern)):
|
|
THREE = set(pattern)
|
|
elif R1.issubset(set(pattern)):
|
|
TWO = set(pattern)
|
|
elif R2.issubset(set(pattern)):
|
|
FIVE = set(pattern)
|
|
for pattern in ZERO_OR_NINE:
|
|
if FOUR.issubset(set(pattern)):
|
|
NINE = set(pattern)
|
|
else:
|
|
ZERO = set(pattern)
|
|
# now that we've decoded our digit patterns, convert the output and sum up.
|
|
number = ''
|
|
for digit in output:
|
|
digit = set(digit)
|
|
if digit == ZERO:
|
|
number += '0'
|
|
elif digit == ONE:
|
|
number += '1'
|
|
elif digit == TWO:
|
|
number += '2'
|
|
elif digit == THREE:
|
|
number += '3'
|
|
elif digit == FOUR:
|
|
number += '4'
|
|
elif digit == FIVE:
|
|
number += '5'
|
|
elif digit == SIX:
|
|
number += '6'
|
|
elif digit == SEVEN:
|
|
number += '7'
|
|
elif digit == EIGHT:
|
|
number += '8'
|
|
elif digit == NINE:
|
|
number += '9'
|
|
part2 += int(number)
|
|
print(part2) |