From 7e1e33c0ba97dd2209187bc384f36c283e9c2c87 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Wed, 9 Dec 2015 11:13:20 +0100 Subject: [PATCH] Solutions for day 9. --- day9-input.txt | 28 ++++++++++++++++++++++ day9.py | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 day9-input.txt create mode 100644 day9.py diff --git a/day9-input.txt b/day9-input.txt new file mode 100644 index 0000000..997758f --- /dev/null +++ b/day9-input.txt @@ -0,0 +1,28 @@ +Tristram to AlphaCentauri = 34 +Tristram to Snowdin = 100 +Tristram to Tambi = 63 +Tristram to Faerun = 108 +Tristram to Norrath = 111 +Tristram to Straylight = 89 +Tristram to Arbre = 132 +AlphaCentauri to Snowdin = 4 +AlphaCentauri to Tambi = 79 +AlphaCentauri to Faerun = 44 +AlphaCentauri to Norrath = 147 +AlphaCentauri to Straylight = 133 +AlphaCentauri to Arbre = 74 +Snowdin to Tambi = 105 +Snowdin to Faerun = 95 +Snowdin to Norrath = 48 +Snowdin to Straylight = 88 +Snowdin to Arbre = 7 +Tambi to Faerun = 68 +Tambi to Norrath = 134 +Tambi to Straylight = 107 +Tambi to Arbre = 40 +Faerun to Norrath = 11 +Faerun to Straylight = 66 +Faerun to Arbre = 144 +Norrath to Straylight = 115 +Norrath to Arbre = 135 +Straylight to Arbre = 127 diff --git a/day9.py b/day9.py new file mode 100644 index 0000000..be88b02 --- /dev/null +++ b/day9.py @@ -0,0 +1,63 @@ +import re +import fileinput + +dist = {} +visited = set() + +def computeMinDistance(startPoint): + visited.add(startPoint) + + if len(dist) == len(visited): + maximum = 0 + minimum = 0 + else: + minimum = None + maximum = 0 + + for i in dist[startPoint]: + if i in visited: + continue + + shortest, longest = computeMinDistance(i) + + if shortest is not None: + shortest += dist[startPoint][i] + longest += dist[startPoint][i] + + if minimum is None: + minimum = shortest + maximum = longest + else: + minimum = min(minimum, shortest) + maximum = max(maximum, longest) + + visited.remove(startPoint) + + return minimum, maximum + + + +linePattern = re.compile(r"(\w+) to (\w+) = (\d+)") + +for line in fileinput.input(): + match = linePattern.match(line) + if match.group(1) not in dist: + dist[match.group(1)] = {} + + if match.group(2) not in dist: + dist[match.group(2)] = {} + + dist[match.group(1)][match.group(2)] = int(match.group(3)) + dist[match.group(2)][match.group(1)] = int(match.group(3)) + +minimum = None +possible = [] +for i in dist: + shortest, longest = computeMinDistance(i) + + if shortest is not None: + possible.append(shortest) + possible.append(longest) + +print "Shortest path is", min(possible) +print "Longest path is", max(possible)