AdventOfCode/2015/09/solution.py

74 lines
2.0 KiB
Python
Raw Normal View History

#!/bin/python3
import sys,time,re,json
from pprint import pprint
sys.path.insert(0, '../../')
from fred import list2int,get_re,nprint,lprint,loadFile,dprint,TSP
start_time = time.time()
input_f = 'input'
part = 2
#########################################
# #
# Part 1 #
# #
#########################################
def constructGraph(input_f):
"""
The graph of cities should look something like this
graph = {
"node": [("dist1", distance1), ("dist", distance2)],
}
"""
inst = []
graph = {}
with open(input_f) as file:
for line in file:
inst = line.rstrip().split(' = ')
inst = inst[0].split(' to ') + [int(inst[1])]
if inst[0] not in graph:
graph[inst[0]] = []
if inst[1] not in graph:
graph[inst[1]] = []
graph[inst[0]].append((inst[1],inst[2]))
graph[inst[1]].append((inst[0],inst[2]))
return graph
if part == 1:
graph = constructGraph(input_f)
shortest = float('inf')
routes = []
cities = set(graph.keys())
for neighbors in graph.values():
for neighbor, _ in neighbors:
cities.add(neighbor)
for c in cities:
print(TSP(graph, c))
shortest = min(shortest,TSP(graph, c)[1])
print(shortest)
#########################################
# #
# Part 2 #
# #
#########################################
if part == 2:
graph = constructGraph(input_f)
#print(graph)
longest = 0
routes = []
cities = set(graph.keys())
for neighbors in graph.values():
for neighbor, _ in neighbors:
cities.add(neighbor)
for c in cities:
longest = max(longest,TSP(graph, c,'longest')[1])
print(longest)
print("--- %s seconds ---" % (time.time() - start_time))