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
|
#!/usr/bin/env python3
# import numpy as np
from functools import reduce
from re import findall
from copy import deepcopy
import sys
# filename = "in/day14.ref"
filename = "in/day14.pzl"
data = open(filename).read()
lines = [line for line in data.rstrip('\n').split('\n')]
G = set()
for line in lines:
for a,b in zip(line.split(' -> '), line.split(' -> ')[1:]):
xs,ys = [int(i) for i in a.split(',')]
xe,ye = [int(i) for i in b.split(',')]
if xe < xs:
xs, xe = xe, xs
if ye < ys:
ys, ye = ye, ys
for x in range(xs, xe+1):
for y in range(ys, ye+1):
G.add((y,x))
max_y = 0
for y,x in G:
max_y = max(max_y, y)
# print('max_y', max_y)
def add_sand(G, part, y=0, x=500):
if part == 1 and y > max_y:
return G
elif part == 2 and y == max_y + 1:
G.add((y,x))
return G
elif (y+1, x) not in G:
return add_sand(G, part, y+1, x)
elif (y+1, x-1) not in G:
return add_sand(G, part, y+1, x-1)
elif (y+1, x+1) not in G:
return add_sand(G, part, y+1, x+1)
elif (y,x) not in G:
G.add((y,x))
return G
return G
start_len = len(G)
for part in [1,2]:
Gp = G.copy()
while True:
prev_len = len(Gp)
Gp = add_sand(Gp, part)
if len(Gp) == prev_len:
break
print(len(Gp) - start_len)
|