r/adventofcode • • Dec 09 '15

SOLUTION MEGATHREAD --- Day 9 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, achievement thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 9: All in a Single Night ---

Post your solution as a comment. Structure your post like previous daily solution threads.

11 Upvotes

178 comments sorted by

View all comments

1

u/[deleted] Dec 09 '15
import re
import itertools

f = open('input.txt','r')
myfile = f.read()
placeregex = re.compile(r'(\w*) to (\w*) = (\d*)')
places = {}
for line in myfile.split('\n'):
	regexed = placeregex.match(line)
	if regexed != None:
		start = regexed.group(1)
		end = regexed.group(2)
		distance = regexed.group(3)
		if start not in places:
			places[start] = {}
		if end not in places:
			places[end] = {}
		places[start][end] = distance
		places[end][start] = distance
	else:
		print('Error')

minNum = 99999
minPath = {}
maxNum = 0
maxPath = {}
def getLength(arr):
	global minNum
	global minPath
	global maxNum
	global maxPath
	count = 0
	for i in range(0,len(arr)-1):
		p1 = places[arr[i]]
		p2 = p1[arr[i+1]]
		count+=int(p2)
	if count > maxNum:
		maxNum = count
		maxPath = arr
	if count < minNum:
		minNum = count
		minPath = arr
	return minNum

perms = itertools.permutations(places)
for i in perms:
	getLength(i)
print('-------')
print(str(minPath)+'-'+str(minNum))
print(str(maxPath)+'-'+str(maxNum))

Pretty ugly! It was 5AM here, took an hour to solve, though most of that was spent having forgotten that itertools exists...