Skip to content

Commit d7f1ec1

Browse files
author
Florian Rohrer
committed
Day 14
1 parent bf242e5 commit d7f1ec1

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
|[Day 11: Monkey in the Middle](https://adventofcode.com/2022/day/11) |[py](/day11/main.py)|
1616
|[Day 12: Hill Climbing Algorithm](https://adventofcode.com/2022/day/12) |[py](/day12/main.py)|
1717
|[Day 13: Distress Signal](https://adventofcode.com/2022/day/13) |[py](/day13/main.py)|
18+
|[Day 14: Regolith Reservoir](https://adventofcode.com/2022/day/14) |[py](/day14/main.py)|
1819

1920
My solutions from previous years:
2021
* [r0f1/adventofcode2020](https://github.com/r0f1/adventofcode2020)

day14/main.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
 (0)