1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
data = [
[[int(d) for d in r.split(",")] for r in dat.split(" -> ")]
for dat in open("input").readlines()
if dat != ""
]
X = 1000
Y = 500
SOURCE = [500, 0]
AIR = 0
ROCK = 1
SAND = 2
RESTED = 3
def rocks(grid, line):
for i, (x, y) in enumerate(line[1:]):
px = line[i][0]
py = line[i][1]
xmax, xmin = max(x, px), min(x, px)
ymax, ymin = max(y, py), min(y, py)
for lx in range(xmin, xmax + 1):
for ly in range(ymin, ymax + 1):
grid[lx][ly] = ROCK
def simulate(grid):
falling = True
while falling:
# new sand drop!
sand = SOURCE.copy()
while True:
if sand[1] >= Y - 1:
falling = False
break
elif grid[sand[0]][sand[1] + 1] == AIR:
sand[1] += 1
elif grid[sand[0] - 1][sand[1] + 1] == AIR:
sand[0] -= 1
sand[1] += 1
elif grid[sand[0] + 1][sand[1] + 1] == AIR:
sand[0] += 1
sand[1] += 1
else:
grid[sand[0]][sand[1]] = RESTED
if sand == SOURCE:
falling = False
break
def solve(grounded):
grid = [[AIR] * Y for i in range(X)]
for line in data:
rocks(grid, line)
if grounded:
ground = max(y for _, y in sum(data, []))
for x in range(X):
grid[x][ground + 2] = ROCK
simulate(grid)
return sum(col.count(RESTED) for col in grid)
print(f"Part 1: {solve(False)}")
print(f"Part 2: {solve(True)}")
|