Guest User

Untitled

a guest
Dec 6th, 2024
731
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | Source Code | 0 0
  1. from itertools import cycle
  2.  
  3. path = "day_06.txt"
  4. # path = "test.txt"
  5.  
  6. with open(path) as f:
  7.     lines = [l.strip() for l in f.readlines()]
  8.  
  9. ROWS = len(lines)
  10. COLS = len(lines[0])
  11.  
  12. directions = {">": (0,1), 'v': (1,0), '<': (0,-1), '^': (-1, 0)}
  13.  
  14. loop = cycle(directions)
  15.  
  16. def reset_loop(loop, char):
  17.     while next(loop) != char:
  18.         continue
  19.  
  20. initial_pos = ()
  21. d = ()
  22. for i in range(ROWS):
  23.     for j in range(COLS):
  24.         if lines[i][j] in directions:
  25.             initial_pos = (i,j)
  26.             d = directions[lines[i][j]]
  27.            
  28.             reset_loop(loop, lines[i][j])
  29.            
  30. def is_inside(lines, pos):
  31.     return 0 <= pos[0] < ROWS and 0<= pos[1] < COLS
  32.  
  33. def walk(lines, pos, d, obstacle, d_loop):
  34.     i,j = pos
  35.     x,y = d
  36.    
  37.     new_pos = (x+i, y+j)
  38.     if is_inside(lines, new_pos) and \
  39.         (lines[new_pos[0]][new_pos[1]] == '#' or new_pos == obstacle):
  40.         return pos, directions[next(d_loop)]
  41.        
  42.     return new_pos, d
  43.  
  44. def evaluate_path(lines, initial_pos, initial_d, obstacle, d_loop):
  45.     inside = True
  46.     in_loop = False
  47.     pos = initial_pos
  48.     d = initial_d
  49.     walked = set()
  50.     loop_detec = set()
  51.     while inside and not in_loop:
  52.         walked.add(pos)
  53.         loop_detec.add((pos, d))
  54.         pos, d = walk(lines, pos, d, obstacle, d_loop)
  55.        
  56.         in_loop = (pos,d) in loop_detec        
  57.         inside = is_inside(lines, pos)
  58.  
  59.     return len(walked), in_loop
  60.  
  61. print( "p1: ", evaluate_path(lines, initial_pos, d, None, loop)[0])
  62.  
  63. # P2 brute force?
  64. p2 = 0
  65. for row in range(ROWS):
  66.     for col in range(COLS):
  67.         reset_loop(loop, lines[initial_pos[0]][initial_pos[1]])
  68.        
  69.         size, in_loop = evaluate_path(lines, initial_pos, d, (row, col), loop)
  70.        
  71.         p2 += 1 if in_loop else 0
  72.         percentage = int((row*ROWS + col)/(ROWS*COLS) * 100)
  73.         print(f'{percentage}%', end='\r')
  74.        
  75. print('100%')
  76.        
  77. print('p2: ', p2)
Advertisement
Add Comment
Please, Sign In to add comment