Guest User

Advent of Code 2023, Day 8 Pt2 Python Attempt

a guest
Dec 13th, 2023
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. class node():
  2.     def __init__(self,name):
  3.         self.name = name
  4.         self.adj_nodes = {}
  5.    
  6.     def add_node(self,name,dir):
  7.         self.adj_nodes[dir] = name
  8.  
  9.     def get_adj_node(self,dir):
  10.         return self.adj_nodes[dir]
  11.  
  12.  
  13. def parttwo(nodes,dir):
  14.     #first find all nodes that end if A or Z
  15.     current_nodes = [x for x in nodes if x.name[-1] == "A"]
  16.     end_nodes = [x.name for x in nodes if x.name[-1] == "Z"]
  17.  
  18.     total_steps = 0
  19.     count = 0
  20.     keep_mapping = True
  21.     while keep_mapping:
  22.        
  23.         if total_steps % 1000000 == 0:
  24.             print(total_steps)
  25.         if count >= len(dir):
  26.             count = 0
  27.         step = dir[count]
  28.         next_list = []
  29.         is_it_over = True
  30.         for n in current_nodes:
  31.             next_list.append(n.get_adj_node(step))
  32.             if next_list[-1] not in end_nodes:
  33.                 is_it_over = False
  34.        
  35.         count +=1
  36.         total_steps +=1
  37.        
  38.         if is_it_over:
  39.             keep_mapping = False
  40.         else:
  41.             current_nodes = []
  42.             for n in next_list:
  43.                 current_nodes.append([x for x in nodes if x.name == n][0])
  44.    
  45.     print(f"Steps to end_nodes is:", total_steps)
  46.  
  47.  
Advertisement
Add Comment
Please, Sign In to add comment