Advertisement
Guest User

AOC day 14

a guest
Dec 14th, 2022
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. inputFile = open('day14.txt', 'r')
  2.  
  3. lines = inputFile.read().split("\n")
  4.  
  5. cave = {}
  6. for line in lines:
  7.     P = [x.split(",") for x in line.split("->")]
  8.     points = [(int(x[0]), int(x[1])) for x in P]
  9.  
  10.     for p1, p2 in zip(points, points[1:]):
  11.         x1, y1 = p1
  12.         x2, y2 = p2
  13.  
  14.         for x in range(min(x1, x2), max(x1, x2) + 1):
  15.             cave[(x, y1)] = "#"
  16.  
  17.         for y in range(min(y1, y2), max(y1, y2) + 1):
  18.             cave[(x1, y)] = "#"
  19.  
  20. def last_y(cave):
  21.     return max(y for (_, y) in cave.keys())
  22.  
  23. def sand_fall(cave):
  24.     x = 500
  25.  
  26.     for y in range(last_y(cave)):
  27.         # down one step
  28.         if (x, y + 1) not in cave:
  29.             continue
  30.         # down left
  31.         elif (x - 1, y + 1) not in cave:
  32.             x -= 1
  33.         # down right
  34.         elif (x + 1, y + 1) not in cave:
  35.             x += 1
  36.         else:
  37.             cave[(x, y)] = "o"
  38.             # stop simulation if we are blocked at starting position
  39.             return (x, y) != (500, 0)
  40.     return False
  41.  
  42. def add_bottom_floor(cave):
  43.     y = last_y(cave) + 2
  44.     for x in range(-1000, 1001):
  45.         cave[(x, y)] = "#"
  46.  
  47. def simulate(has_bottom_floor):
  48.     if has_bottom_floor:
  49.         add_bottom_floor(cave)
  50.  
  51.     while sand_fall(cave):
  52.         pass
  53.  
  54.     return cave
  55.  
  56. # part 1
  57. p1 = sum(v == "o" for v in simulate(False).values())
  58. print(p1)
  59.  
  60. p2 = sum(v == "o" for v in simulate(True).values())
  61. print(p2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement