Advertisement
hhoppe

Advent of code 2023 day 25 fast

Dec 25th, 2023
1,013
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. def day25(s, num_random_edges=100):
  2.   graph = networkx.Graph()
  3.   for line in s.splitlines():
  4.     node, other_nodes = line.split(':')
  5.     for node2 in other_nodes.split():
  6.       graph.add_edge(node, node2)
  7.  
  8.   # The graph in the puzzle input has a dumbbell connectivity structure.
  9.   # Therefore, a heuristic algorithm is to examine the shortest paths between
  10.   # many random pairs of nodes and find the most common edges.
  11.  
  12.   rng = np.random.default_rng(0)
  13.   edge_counts = collections.Counter()
  14.   nodes = np.array(list(graph.nodes()))
  15.  
  16.   for _ in range(num_random_edges):
  17.     node_pair = rng.choice(nodes, size=2, replace=False)
  18.     path = networkx.shortest_path(graph, source=node_pair[0], target=node_pair[1])
  19.     for edge in itertools.pairwise(path):
  20.       edge_counts[tuple(sorted(edge))] += 1
  21.  
  22.   for (node1, node2), _ in edge_counts.most_common(3):
  23.     graph.remove_edge(node1, node2)
  24.   component1, component2 = networkx.connected_components(graph)
  25.   return len(component1) * len(component2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement