advent_of_code/2021/8/8_2.py

84 lines
2.8 KiB
Python
Raw Normal View History

2021-12-09 00:02:38 +01:00
#!/usr/bin/env python
# 2021 - Advent Of Code - 8 part 2
2022-11-30 01:48:52 +01:00
# 2022: cheat for pylint to start fresh for 2022
# pylint: disable=no-member
2021-12-09 00:02:38 +01:00
# acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf
def parse_file(file):
numbers_list = []
outputs = []
2022-04-05 13:27:24 +02:00
with open(file, encoding="utf-8") as f:
2021-12-09 00:02:38 +01:00
for line in f.readlines():
numbers, output = line.strip().split(' | ')
numbers_list.append(numbers)
outputs.append(output)
return numbers_list, outputs
2021-12-13 05:38:24 +01:00
def print_numbers(id_num):
2021-12-09 00:02:38 +01:00
print('identified numbers:')
for i in range(10):
2021-12-13 05:38:24 +01:00
print(f'{i} is {id_num[i]}')
2021-12-09 00:02:38 +01:00
# entries, displays = parse_file('input_example1.txt')
entries, displays = parse_file('input.txt')
output_sum = 0
for entry, display in zip(entries, displays):
identified_numbers = [-1] * 10
words = entry.split(' ')
# size of pattern for 1, 4, 7 and 8 is unique
identified_numbers[1] = set([x for x in words if len(x) == 2][0])
identified_numbers[7] = set([x for x in words if len(x) == 3][0])
identified_numbers[4] = set([x for x in words if len(x) == 4][0])
identified_numbers[8] = set([x for x in words if len(x) == 7][0])
# size 6 pattern that doesn't include 4, nor 1 -> 6
# size 6 pattern that includes 4 and 1 -> 9
# the remaining size 6 pattern -> 0
2021-12-12 17:23:29 +01:00
size_six = {x for x in words if len(x) == 6}
2021-12-09 00:02:38 +01:00
for s in size_six:
if identified_numbers[1].issubset(s) and identified_numbers[4].issubset(s):
identified_numbers[9] = s
if not identified_numbers[1].issubset(s) and not identified_numbers[4].issubset(s):
identified_numbers[6] = s
size_six.remove(identified_numbers[9])
identified_numbers[9] = set(identified_numbers[9])
size_six.remove(identified_numbers[6])
identified_numbers[6] = set(identified_numbers[6])
identified_numbers[0] = set(next(iter(size_six)))
# size 5 pattern that includes 7 -> 3
# size 5 pattern that only missed one element to be a 9 pattern -> 5
# the remaining size 5 pattern -> 2
2021-12-12 17:23:29 +01:00
size_five = {x for x in words if len(x) == 5}
2021-12-09 00:02:38 +01:00
for s in size_five:
if identified_numbers[7].issubset(s):
identified_numbers[3] = s
size_five.remove(identified_numbers[3])
identified_numbers[3] = set(identified_numbers[3])
for s in size_five:
if len(identified_numbers[9] - set(s)) == 1:
identified_numbers[5] = s
break
size_five.remove(identified_numbers[5])
identified_numbers[5] = set(identified_numbers[5])
identified_numbers[2] = set(next(iter(size_five)))
# print_numbers(identified_numbers)
words = display.split(' ')
str_num = ""
for d in words:
n = identified_numbers.index(set(d))
str_num += str(n)
output_sum += int(str_num)
print(f'output_sum: {output_sum}')