From 673f9a02051150c415ea702f4f2ed83b7b3e1222 Mon Sep 17 00:00:00 2001 From: Thibaud Date: Tue, 2 Jun 2026 13:25:23 +0200 Subject: [PATCH] 2015 day 9 --- adventofcode/2015/day9/day9.py | 36 ++++++++++++++++++++++++++++++++ adventofcode/2024/day18/day18.py | 5 ++++- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 adventofcode/2015/day9/day9.py diff --git a/adventofcode/2015/day9/day9.py b/adventofcode/2015/day9/day9.py new file mode 100644 index 0000000..859c960 --- /dev/null +++ b/adventofcode/2015/day9/day9.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +import fileinput +from collections import defaultdict +from itertools import permutations + + +def parse_locations(inp: list[str]) -> dict[str, dict[str, int]]: + "parse list of location pairs into adjacency map" + locations = defaultdict(dict) + for line in inp: + places, dist = line.split(" = ") + place_from, place_to = places.split(" to ") + locations[place_from][place_to] = int(dist) + locations[place_to][place_from] = int(dist) # store both directions + return locations + + +def main(inp): + "brute force over permutations of cities, keeping track of min and max cost" + locations = parse_locations(inp) + min_cost = 99999 + max_cost = 0 + for perm in permutations(locations): + cost = 0 + # iterate over pairs of cities and get cost from adjacency map + for city_a, city_b in zip(perm, perm[1:]): + cost += locations[city_a][city_b] + min_cost = min(cost, min_cost) + max_cost = max(cost, max_cost) + print("Part 1: ", min_cost) + print("Part 2: ", max_cost) + + +if __name__ == "__main__": + lines = [x.rstrip() for x in fileinput.input()] + main(lines) diff --git a/adventofcode/2024/day18/day18.py b/adventofcode/2024/day18/day18.py index f083b38..82ddb15 100644 --- a/adventofcode/2024/day18/day18.py +++ b/adventofcode/2024/day18/day18.py @@ -28,7 +28,10 @@ def can_reach(pos, obstacles, grid_size): return False -def search(obstacles, start, goal, grid_size): # could just use bfs? +def search(obstacles, start, goal, grid_size): + """ + Dijkstra's algorithm. Could as well use BFS since step costs are uniform. (n = Node(new_pos, node.cost + 1)) + """ queue = [Node(start)] visited = set() i = 0