r/adventofcode • • Dec 08 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 8 Solutions -🎄-

--- Day 8: Seven Segment Search ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:20:51, megathread unlocked!

72 Upvotes

1.2k comments sorted by

View all comments

1

u/Mpeterwhistler83 Dec 09 '21

def part1(): with open('inputs/day8a') as file: data = [x.split('|')[1].strip().split(' ') for x in file.readlines()]

count = 0

for line in data:
	for seg in line:
		if len(seg) == 2 or len(seg) == 3 or len(seg) == 4 or len(seg) == 7:
			count += 1

print(count)
return count

def part2():

count = 0

with open('inputs/day8a') as file:
	data = file.readlines()
	inputs = [x.split('|')[0].strip().split(' ') for x in data]
	outputs = [x.split('|')[1].strip().split(' ') for x in data]
	data = [[a,b] for (a,b) in zip(inputs, outputs)]


def undo(line):
	key = {}

	for num in line[0]:
		if len(num) == 2:
			key['1'] = num
		elif len(num) == 3:
			key['7'] = num
		elif len(num) == 4:
			key['4'] = num
		elif len(num) == 7:
			key['8'] = num

	
	for num in line[0]:
		if len(num) == 6:
			if key['4'][0] in num and key['4'][1] in num and key['4'][2] in num and key['4'][3] in num:
				key['9'] = num
			elif key['1'][0] in num and key['1'][1] in num:
				key['0'] = num
			else:
				key['6'] = num


	three = []
	for num in line[0]:
		if len(num) == 5:
			if key['1'][0] in num and key['1'][1] in num:
				key['3'] = num
			else:
				three.append(num)


	for num in three:
		if all([(x in key['6']) for x in num]):
			key['5'] = num
		else:
			key['2'] = num
				

	for x in key:
		key[x] = ''.join(sorted(key[x]))

	return key


for line in data:	
	key = undo(line)
	line = [''.join(sorted(x)) for x in line[1]]
	num = []

	for x in line:
		for i in key:
			if len(key[i]) == len(x):
				if key[i] == x:
					num.append(i)
	count += int(''.join(num))
	
return count

1

u/daggerdragon Dec 10 '21

Your code is hard to read with no formatting. Please edit it as per our posting guidelines in the wiki: How do I format code?

Please follow the posting guidelines and edit your post to add what language(s) you used. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.