Skip to content

Commit

Permalink
Add advent of code 2022 day 14 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
iandioch committed Dec 14, 2022
1 parent b5b5c8a commit 9efa21c
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions advent_of_code/2022/14/part1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import sys

DEBUG = False

def parse():
BUFFER_TOP = 5
segs = []
minx, miny, maxx, maxy = 500, 500, 0, 0

for line in sys.stdin.readlines():
line = line.strip()
point = [tuple(map(int, p.split(','))) for p in line.split(' -> ')]
for i in range(1, len(point)):
segs.append((point[i-1], point[i]))
print(segs[-1])
minx = min(min(s[0][0], s[1][0]) for s in segs) - 1
maxx = max(max(s[0][0], s[1][0]) for s in segs) + 1
miny = min(min(s[0][1], s[1][1]) for s in segs) - BUFFER_TOP
maxy = max(max(s[0][1], s[1][1]) for s in segs)

grid = [['.' for _ in range(minx, maxx+1)] for _ in range(miny, maxy+1)]
for start, end in segs:
if start[0] == end[0]:
if start[1] > end[1]:
start, end = end, start
for y in range(start[1]-miny, end[1]-miny+1):
grid[y][start[0]-minx] = '#'
else:
if start[0] > end[0]:
start, end = end, start
for x in range(start[0]-minx, end[0]-minx+1):
grid[start[1]-miny][x] = '#'
print('-'*len(grid[0]))
for row in grid:
print(''.join(row))

return grid, 500 - minx

def how_much_sand(grid, sandx):
def add_sand():
x = sandx
y = 0
while True:
if y + 1 >= len(grid):
return False

if DEBUG:
print('-'*len(grid[0]))
print('in sand:', y, x)
for j, row in enumerate(grid):
print(''.join('+' if (i==x and j==y) else c for i, c in enumerate(row)))
if grid[y+1][x] == '.':
y += 1
continue
if grid[y+1][x-1] == '.':
y += 1
x -= 1
continue
if grid[y+1][x+1] == '.':
y += 1
x += 1
continue
grid[y][x] = 'o'
return True

ans = 0
while True:
if not add_sand():
break
ans += 1
if DEBUG:
print('-'*len(grid[0]))
for row in grid:
print(''.join(row))

print()
for row in grid:
print(''.join(row))
return ans

def main():
grid, sandx = parse()
print(how_much_sand(grid, sandx))

main()

0 comments on commit 9efa21c

Please sign in to comment.