From 00df2153d4f33743b5c4b07370265c974c00afa1 Mon Sep 17 00:00:00 2001 From: Lachlan Meyer Date: Tue, 17 Dec 2024 09:32:13 +1100 Subject: [PATCH] 16-1 --- 2024/16/16-1.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2024/16/testinput.txt | 15 +++++++++++++++ 2024/16/testinput2.txt | 17 +++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 2024/16/16-1.py create mode 100644 2024/16/testinput.txt create mode 100644 2024/16/testinput2.txt diff --git a/2024/16/16-1.py b/2024/16/16-1.py new file mode 100644 index 0000000..f9a72a8 --- /dev/null +++ b/2024/16/16-1.py @@ -0,0 +1,42 @@ +import networkx as nx + +directions = (1, -1, 1j, -1j) # use imaginary numbers for east<->west + +with open('2024/16/input.txt') as f: + g = nx.DiGraph() + for i, line in enumerate(f): + line = line.strip() + for j, char in enumerate(line): + if char == '#': + continue + node = i + 1j * j + + if char == 'E': + e = node + if char == 'S': + s = (node, 1j) # reindeer starts pointing west + + for nodeDir in directions: + g.add_node((node, nodeDir)) + + for node, nodeDir in g.nodes: + if (node + nodeDir, nodeDir) in g.nodes: + # orthogonally connected in the same direction as previous node + # eg, connect node A's north direction with node B's north + # no need to connect A's north to B's south - it'd be redundant + g.add_edge((node, nodeDir), (node + nodeDir, nodeDir), weight=1) + for rotation in -1j, 1j: + # connect 90 degree corners + # using i, since i**2 = 1 so it'll respect a turn + g.add_edge((node, nodeDir), (node, nodeDir * rotation), weight=1000) + + # need to make a new endpoint otherwise the exit will not be found + for direction in directions: + # we appear to have an off-by-one problem, remove the last move to the exit + g.add_edge((e, direction), 'end', weight=0) + + shortestPath = nx.shortest_path(g, s, 'end', weight='weight') + weight = nx.path_weight(g, shortestPath, weight='weight') + + print(shortestPath) + print(weight) \ No newline at end of file diff --git a/2024/16/testinput.txt b/2024/16/testinput.txt new file mode 100644 index 0000000..6a5bb85 --- /dev/null +++ b/2024/16/testinput.txt @@ -0,0 +1,15 @@ +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### \ No newline at end of file diff --git a/2024/16/testinput2.txt b/2024/16/testinput2.txt new file mode 100644 index 0000000..54f4cd7 --- /dev/null +++ b/2024/16/testinput2.txt @@ -0,0 +1,17 @@ +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# \ No newline at end of file