|
| 1 | +import numpy as np |
| 2 | +from more_itertools import flatten |
| 3 | +from more_itertools import pairwise |
| 4 | +from PIL import Image, ImageOps |
| 5 | +from skimage.draw import line as draw_line |
| 6 | + |
| 7 | +with open("input.txt") as f: |
| 8 | + lines = [[[int(c) for c in k.split(",")] for k in l.split(" -> ")] for l in f] |
| 9 | + |
| 10 | +min_x, min_y = min([x for x, _ in flatten(lines)]+[500]), min([y for _, y in flatten(lines)]+[0]) |
| 11 | +max_x, max_y = max([x for x, _ in flatten(lines)]+[500]), max([y for _, y in flatten(lines)]+[0]) |
| 12 | + |
| 13 | +dim_x, dim_y = (max_x - min_x)+1, (max_y - min_y)+3 |
| 14 | + |
| 15 | +grid = np.zeros((dim_y, dim_x), dtype="uint8") |
| 16 | +for line in lines: |
| 17 | + for a, b in pairwise(line): |
| 18 | + rr, cc = draw_line(a[1]-min_y, a[0]-min_x, b[1]-min_y, b[0]-min_x) |
| 19 | + grid[rr, cc] = 1 |
| 20 | + |
| 21 | +add_border = 300 |
| 22 | +grid = np.array(ImageOps.expand(Image.fromarray(grid), border=(add_border,0,add_border,0), fill=0)) |
| 23 | +rr, cc = draw_line(dim_y-1, 0, dim_y-1, dim_x-1+add_border*2) |
| 24 | +grid[rr, cc] = 1 |
| 25 | + |
| 26 | +offset_x, offset_y = add_border, 0 |
| 27 | + |
| 28 | +generate_new_sand = True |
| 29 | +init_pos_y, init_pos_x = 0-min_y+offset_y, 500-min_x+offset_x |
| 30 | +try: |
| 31 | + while True: |
| 32 | + if generate_new_sand: |
| 33 | + if grid[init_pos_y, init_pos_x] == 3: |
| 34 | + break |
| 35 | + grid[init_pos_y, init_pos_x] = 2 |
| 36 | + pos_y, pos_x = init_pos_y, init_pos_x |
| 37 | + generate_new_sand = False |
| 38 | + else: |
| 39 | + pos_y, pos_x = new_pos_y, new_pos_x |
| 40 | + |
| 41 | + for new_pos_y, new_pos_x in [(pos_y+1, pos_x), (pos_y+1, pos_x-1), (pos_y+1, pos_x+1)]: |
| 42 | + # if new_pos_x == -1: |
| 43 | + # raise Exception() |
| 44 | + if grid[new_pos_y, new_pos_x] == 0: |
| 45 | + grid[pos_y, pos_x] = 0 |
| 46 | + grid[new_pos_y, new_pos_x] = 2 |
| 47 | + break |
| 48 | + else: |
| 49 | + grid[pos_y, pos_x] = 3 |
| 50 | + generate_new_sand = True |
| 51 | +except: |
| 52 | + pass |
| 53 | + |
| 54 | +print(np.sum([grid == 3])) |
0 commit comments