Advertisement
kenan238

Untitled

Dec 7th, 2024
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. # aoc day 6
  2.  
  3. import math
  4.  
  5. with open("data.txt") as f:
  6.   groups = [[*x] for x in f.read().split("\n")]
  7.  
  8. def get_cell(x, y):
  9.   return groups[y][x]
  10. def set_cell(x, y, value):
  11.   groups[y][x] = value
  12. def in_bounds(x, y):
  13.   return x >= 0 and x < len(groups[0]) and y >= 0 and y < len(groups)
  14. def get_pos_of_celltype(cell):
  15.   for y in range(len(groups)):
  16.     for x in range(len(groups[y])):
  17.       if get_cell(x, y) == cell:
  18.         return (x, y)
  19.  
  20. def guard_step(pos, angle):
  21.   x, y = pos
  22.   xi = int(math.cos(math.radians(angle)))
  23.   yi = int(math.sin(math.radians(angle)))
  24.   x += xi
  25.   y += yi
  26.   return (int(x), int(y))
  27.  
  28. def show_path(visited):
  29.   for y in range(len(groups)):
  30.     for x in range(len(groups[y])):
  31.       if (x, y) in visited:
  32.         print("X", end="")
  33.       else:
  34.         print(groups[y][x], end="")
  35.     print()
  36.  
  37. guard = get_pos_of_celltype("^")
  38. def simulate_guard(pos):
  39.   # keep walking until we hit a wall, then turn 90 degrees
  40.  
  41.   angle = -90
  42.   x, y = pos
  43.  
  44.   visited = set()
  45.   visited.add((x, y))
  46.   states = {}
  47.  
  48.   while in_bounds(x, y):
  49.     future_x, future_y = guard_step((x, y), angle)
  50.     if not in_bounds(future_x, future_y):
  51.       break
  52.  
  53.     # look ahead
  54.     if get_cell(future_x, future_y) == "#":
  55.       angle += 90
  56.  
  57.     x, y = guard_step((x, y), angle)
  58.     visited.add((x, y))
  59.  
  60.     state = (x, y, angle % 360)
  61.     states[state] = states.get(state, 0) + 1
  62.  
  63.     if states[state] > 4:
  64.       return visited, True
  65.  
  66.     #show_path(visited)
  67.   return visited, False
  68.  
  69.  
  70. def show_all_visited_cells(visited):
  71.   for y in range(len(groups)):
  72.     for x in range(len(groups[y])):
  73.       if (x, y) in visited:
  74.         print("X", end="")
  75.       else:
  76.         print(groups[y][x], end="")
  77.     print()
  78.  
  79. visited, loop = simulate_guard(guard)
  80. print("Part 1", len(visited))
  81.  
  82. # Part 2
  83.  
  84. total = 0
  85.  
  86. for seen in visited:
  87.   if get_cell(*seen) == "#":
  88.     continue
  89.   set_cell(*seen, "#")
  90.   visited, loop = simulate_guard(guard)
  91.   set_cell(*seen, ".")
  92.   if loop:
  93.     total += 1
  94.     continue
  95.  
  96. print("Part 2", total)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement