Created
December 21, 2024 22:47
-
-
Save nickponline/e481e6a7760230606f84c5e444a10c3f to your computer and use it in GitHub Desktop.
Advent of Code 2024 Day 21 Part 1 + Part 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://adventofcode.com/2024/day/21 | |
| import networkx as nx | |
| from functools import cache | |
| import collections | |
| # NUM_BOTS = 2 | |
| NUM_BOTS = 25 | |
| KK = [ | |
| ['7', '8', '9'], | |
| ['4', '5', '6'], | |
| ['1', '2', '3'], | |
| [' ', '0', 'A'] | |
| ] | |
| AA = [ | |
| [' ' , '^', 'A'], | |
| ['<', 'v', '>'], | |
| ] | |
| def get_paths(grid): | |
| G = nx.DiGraph() | |
| for i, row in enumerate(grid): | |
| for j, key in enumerate(row): | |
| if key == ' ': | |
| continue | |
| G.add_node(key, pos=(i,j)) | |
| for di, dj, direction in [(0,1,'>'), (0,-1,'<'), (1,0,'v'), (-1,0,'^')]: | |
| ni, nj = i + di, j + dj | |
| if 0 <= ni < len(grid) and 0 <= nj < len(row) and grid[ni][nj] != ' ': | |
| G.add_edge(key, grid[ni][nj], direction=direction) | |
| # Find all shortest paths | |
| paths = collections.defaultdict(list) | |
| for start in G.nodes(): | |
| for end in G.nodes(): | |
| if start != end: | |
| raw_paths = list(nx.all_shortest_paths(G, start, end)) | |
| for path in raw_paths: | |
| directions = [ G[path[i]][path[i+1]]['direction'] for i in range(len(path)-1)] | |
| paths[(start, end)].append(''.join(directions)) | |
| return paths | |
| @cache | |
| def minimum_rewrite(level, text): | |
| if level == NUM_BOTS + 1: | |
| return len(text) | |
| PM = K if level == 0 else A | |
| k_total = 0 | |
| for start, end in zip('A'+text, text): | |
| minks = [ minimum_rewrite(level+1, path + 'A') for path in PM[(start, end)]] | |
| minks = [ k for k in minks if k is not None] | |
| k_total += min(minks) if minks else 1 | |
| return k_total | |
| with open('2024-21.in') as f: | |
| codes = [line.strip() for line in f.readlines() if line.strip()] | |
| K = get_paths(KK) | |
| A = get_paths(AA) | |
| total = 0 | |
| for code in codes: | |
| ordinal = int("".join([c for c in code if c.isdigit()])) | |
| min_len = minimum_rewrite(0, code) | |
| total += ordinal * min_len | |
| print(total) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment