-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.py
61 lines (50 loc) · 1.37 KB
/
day14.py
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
DATA = open('day14.txt').read()
AIR, ROCK, SAND = 0, 1, 2
grid = [[AIR] * 1000 for _ in range(1000)]
y_max = 0
for path in ([tuple(map(int, coord.split(','))) for coord in line.split(' -> ')]
for line in DATA.splitlines()):
for (x0, y0), (x1, y1) in zip(path[:-1], path[1:]):
y_max = max(y_max, y0, y1)
if x0 > x1:
x0, x1 = x1, x0
if y0 > y1:
y0, y1 = y1, y0
if x0 == x1:
for y in range(y0, y1 + 1):
grid[y][x0] = ROCK
if y0 == y1:
for x in range(x0, x1 + 1):
grid[y0][x] = ROCK
def insert(x, y, abyss):
if y == y_max + 1:
if not abyss:
grid[y][x] = SAND
return False
if grid[y + 1][x] == AIR:
return insert(x, y + 1, abyss)
elif grid[y + 1][x - 1] == AIR:
return insert(x - 1, y + 1, abyss)
elif grid[y + 1][x + 1] == AIR:
return insert(x + 1, y + 1, abyss)
grid[y][x] = SAND
return True
def part1():
result = 0
while insert(500, 0, True):
result += 1
return result
def part2():
result = 0
while grid[0][500] == AIR:
insert(500, 0, False)
result += 1
return result
grid_input = [row[:] for row in grid]
result = part1()
print(result)
assert result == 838
grid = grid_input
result = part2()
print(result)
assert result == 27539