Solve 2015 days 8-10.

This commit is contained in:
2024-01-30 19:29:31 -05:00
parent 4f9ffa7257
commit 0dfb4f974a
4 changed files with 107 additions and 1 deletions

42
2015/d9.py Normal file
View File

@@ -0,0 +1,42 @@
from lib import *
from typing import Iterator
# Just for fun instead of using itertools.permutations.
def permutations(xs) -> Iterator:
assert len(xs) > 0
if len(xs) == 1:
yield xs
else:
x = xs.pop()
for p in permutations(xs):
for i in range(len(p) + 1):
pn = list(p)
pn.insert(i, x)
yield pn
part_1 = False
data = open(0).read()
dists = {}
nodes = set()
for line in data.splitlines():
path, dist = line.split(" = ")
dist = int(dist)
a, b = path.split(" to ")
nodes.add(a)
nodes.add(b)
dists[(a, b)] = dist
dists[(b, a)] = dist
if part_1:
mdist = 10**12
for route in permutations(nodes):
dist = sum([dists[(route[i], route[i + 1])] for i in range(len(route) - 1)])
mdist = min(dist, mdist)
print(mdist)
else:
mdist = 0
for route in permutations(nodes):
dist = sum([dists[(route[i], route[i + 1])] for i in range(len(route) - 1)])
mdist = max(dist, mdist)
print(mdist)