Advertisement
hhoppe

Advent of code 2024 day 23 visualization

Dec 23rd, 2024
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. def day23_visualize(s):
  2.   graph = networkx.Graph()
  3.   graph.add_edges_from(line.split('-') for line in s.splitlines())
  4.  
  5.   def get_triangles(graph):
  6.     for a in graph:
  7.       for b in graph.neighbors(a):
  8.         if b > a:
  9.           for c in graph.neighbors(a):
  10.             if c > b and graph.has_edge(b, c):
  11.               yield a, b, c
  12.  
  13.   triangles = get_triangles(graph)
  14.   sought_triangles = [t for t in triangles if any(node[0] == 't' for node in t)]
  15.  
  16.   largest_clique = max(networkx.find_cliques(graph), key=len)
  17.  
  18.   pos = networkx.nx_agraph.graphviz_layout(graph, prog='neato', args='-Gstart=1')  # Requires pygraphviz.
  19.   plot_args: Any = dict(figsize=(12, 12), dpi=80)
  20.   draw_args = dict(node_size=60, width=0.3)
  21.  
  22.   if 1:  # First plot.
  23.     fig, ax = plt.subplots(**plot_args)
  24.     ax.set_aspect('equal')
  25.     node_color = [('red' if node[0] == 't' else 'C0') for node in graph]
  26.     networkx.draw(graph, pos, node_color=node_color, **draw_args)
  27.  
  28.     # Draw triangles.
  29.     for triangle in sought_triangles:
  30.       vertices = [pos[node] for node in triangle]
  31.       # Create and add a semi-transparent triangle.
  32.       poly = matplotlib.patches.Polygon(vertices, alpha=0.03, facecolor='green', edgecolor='none')
  33.       ax.add_patch(poly)
  34.  
  35.     fig.tight_layout(pad=0)
  36.  
  37.   if 1:  # Second plot.
  38.     fig, ax = plt.subplots(**plot_args)
  39.     ax.set_aspect('equal')
  40.     node_color = [('red' if node in largest_clique else 'C0') for node in graph]
  41.     networkx.draw(graph, pos, node_color=node_color, **draw_args)
  42.  
  43.     fig.tight_layout(pad=0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement