Guest User

AoC 2025 day 11 part 2

a guest
Dec 11th, 2025
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | Source Code | 0 0
  1. from collections import defaultdict
  2.  
  3.  
  4. def get_map(file_path):
  5.     """
  6.    Read the mapping file and build a dictionary where each node maps to a
  7.    dictionary of connected nodes with integer weights (1 by default).
  8.    After loading, simplify the map by propagating vector values except for
  9.    specific protected nodes.
  10.    """
  11.     output = {}
  12.     for line in open(file_path).read().strip().split('\n'):
  13.         left, right = line.strip().split(': ')
  14.         df = defaultdict(int)
  15.         for x in right.split(' '):
  16.             df[x] = 1
  17.         output[left] = df
  18.  
  19.     # Simplification stage
  20.     for source_node, vector in tuple(output.items()):
  21.         if source_node in ('svr', 'dac', 'fft'):
  22.             continue
  23.         for target_node, base in output.items():
  24.             output[target_node] = compute_vector(source_node, base, vector)
  25.         del output[source_node]
  26.  
  27.     return output
  28.  
  29.  
  30. def compute_vector(node, base, vector):
  31.     """
  32.    Compute the propagation effect of removing a node from a base vector:
  33.    - If node is not in the base, return base unchanged.
  34.    - Multiply the vector by the factor found in base[node].
  35.    - Remove node from base and add the multiplied vector.
  36.    """
  37.     if node not in base:
  38.         return base
  39.  
  40.     factor = base[node]
  41.     del base[node]
  42.  
  43.     multiplied = {k: v * factor for k, v in vector.items()}
  44.  
  45.     for k, v in multiplied.items():
  46.         base[k] += v
  47.  
  48.     return base
  49.  
  50.  
  51. def rec(path, power=1):
  52.     """
  53.    Recursive traversal through the computed map.
  54.    Accumulate global total when a valid path to 'out' is reached
  55.    containing both 'dac' and 'fft'.
  56.    """
  57.     global total
  58.     node = path[-1]
  59.  
  60.     if node == 'out':
  61.         if 'dac' in path and 'fft' in path:
  62.             total += power
  63.             return True
  64.         return
  65.  
  66.     for nxt, p in mapping[node].items():
  67.         rec(path + (nxt,), power * p)
  68.  
  69.  
  70. def main():
  71.     """
  72.    Main execution entry: performs the recursive enumeration of paths.
  73.    """
  74.     rec(('svr',))
  75.  
  76.  
  77. if __name__ == "__main__":
  78.     print('\n' * 10)
  79.     total = 0
  80.  
  81.     mapping = get_map('input.txt')
  82.  
  83.     main()
  84.     print('solution:', total)
  85.  
Advertisement
Add Comment
Please, Sign In to add comment