|
| 1 | +def sandfall(part1, paths, max_y): |
| 2 | + occupied = paths.copy() |
| 3 | + while True: |
| 4 | + sand_x, sand_y = 500, 0 |
| 5 | + |
| 6 | + if (500, 0) in occupied: |
| 7 | + return len(occupied - paths) |
| 8 | + |
| 9 | + while True: |
| 10 | + if (sand_x, sand_y + 1) not in occupied and sand_y < max_y: |
| 11 | + sand_y += 1 |
| 12 | + elif (sand_x - 1, sand_y + 1) not in occupied and sand_y < max_y: |
| 13 | + sand_y += 1 |
| 14 | + sand_x -= 1 |
| 15 | + if sand_y == max_y and part1: |
| 16 | + return len(occupied - paths)-1 |
| 17 | + elif (sand_x + 1, sand_y + 1) not in occupied and sand_y < max_y: |
| 18 | + sand_y += 1 |
| 19 | + sand_x += 1 |
| 20 | + if sand_y == max_y and part1: |
| 21 | + return len(occupied - paths)-1 |
| 22 | + else: |
| 23 | + occupied.add((sand_x, sand_y)) |
| 24 | + break |
| 25 | + |
| 26 | + |
| 27 | +with open('inputs/day14.txt') as data: |
| 28 | + paths = set() |
| 29 | + max_y = 0 |
| 30 | + for path in data.read().splitlines(): |
| 31 | + path = path.split(" -> ") |
| 32 | + for i in range(1, len(path)): |
| 33 | + x, y = [int(p) for p in path[i].split(",")] |
| 34 | + prev_x, prev_y = [int(p) for p in path[i - 1].split(",")] |
| 35 | + max_y = max(y, prev_y, max_y) |
| 36 | + if x == prev_x: |
| 37 | + for dy in range(min(prev_y, y), max(prev_y, y) + 1): |
| 38 | + paths.add((x, dy)) |
| 39 | + else: |
| 40 | + for dx in range(min(prev_x, x), max(prev_x, x) + 1): |
| 41 | + paths.add((dx, y)) |
| 42 | + |
| 43 | + print("Part 1:", sandfall(True, paths, max_y)) |
| 44 | + max_y += 1 |
| 45 | + print("Part 2:", sandfall(False, paths, max_y)) |
0 commit comments