advent_of_code/2023/day18/main.py

125 lines
3.2 KiB
Python

import re
from tracemalloc import start
import numpy as np
import turtle
wn = turtle.Screen()
wn.bgcolor("light green")
wn.title("Turtle")
# skk = turtle.Turtle()
wn.colormode(255)
dir = {"L": [-1,0], "R": [1,0], "U": [0,-1], "D": [0,1]}
# f = open('test.txt', 'r')
f = open('input.txt', 'r')
content = f.read()
lines = content.splitlines()
current_pos = [0,0]
positions = []
positions.append(current_pos)
extra = 1
turtle.setpos(*current_pos)
for line in lines:
parts = line.split(" ")
new_dir = dir[parts[0]]
current_pos = [current_pos[0] + int(parts[1])*new_dir[0], current_pos[1] + int(parts[1])*new_dir[1]]
positions.append(current_pos)
if parts[0] == "R" or parts[0] == "U":
extra += int(parts[1])
print(current_pos)
color_array = []
color_raw = parts[2].strip("(#)")
for i in range(3):
color_array.append(int(color_raw[i*2:i*2+2], 16))
# print(color_array)
# turtle.color(*color_array)
# turtle.goto(*current_pos)
print(parts)
pos_np = np.array(positions)
w = np.max(pos_np[:,0]) - np.min(pos_np[:,0])
h = np.max(pos_np[:,1]) - np.min(pos_np[:,1])
pos_np = pos_np-np.array([np.min(pos_np[:,0]), np.min(pos_np[:,1])])
print(pos_np)
grid = np.zeros((w+1,h+1))
for pos_idx in range(1,len(pos_np)):
max_x = max(pos_np[pos_idx][0], pos_np[pos_idx-1][0])
min_x = min(pos_np[pos_idx][0], pos_np[pos_idx-1][0])
max_y = max(pos_np[pos_idx][1], pos_np[pos_idx-1][1])
min_y = min(pos_np[pos_idx][1], pos_np[pos_idx-1][1])
# grid[min_x:max_x+1,min_y:max_y+1]= 1
sign = 1 if pos_np[pos_idx][0] - pos_np[pos_idx-1][0] >= 0 else -1
# grid[min_x:max_x+1,min_y:max_y+1]= sign
if max_y - min_y == 0:
grid[min_x:max_x+1,min_y:max_y+1]= sign
else:
grid[min_x:max_x+1,min_y+1:max_y]= 1
# grid[min_x:max_x+1,max_y-1]= 1
print(grid)
from matplotlib import pyplot as plt
plt.imshow(grid)
plt.show()
print(grid.sum())
for row in range(len(grid)):
inside = False
for col in range(len(grid[0])):
if grid[row][col] == 1:
inside = True
elif grid[row][col] == -1:
inside = False
grid[row][col] = 1
else:
if inside:
grid[row][col] = 1
# grid[0][0] = -1
# for row in range(len(grid)):
# max_x = min(row+1, len(grid)-1)
# min_x = max(row-1, 0)
# inside = False
# for col in range(len(grid[0])):
# if grid[row][col] != 1:
# max_y = min(col+1, len(grid)-1)
# min_y = max(col-1, 0)
# grid[row][col] = np.min(grid[min_x:max_x+1,min_y:max_y+1])
plt.imshow(grid)
plt.show()
# turtle.done()
f.close()
print(grid.sum())
x=pos_np[:,0]
y=pos_np[:,1]
i=np.arange(len(x))
def calc_area(points):
a = 0
for i in range(1, len(points)):
temp = points[i]-points[i-1]
# prinet(temp)
a += temp[0]*points[i][1]#*temp[1]
# if temp[0] == 0:
# a += np.abs(temp[1])*points[i][0]#*temp[1]
# else:
# a += np.abs(temp[0])*points[i][1]#*temp[1]
return a
Area = calc_area(pos_np)
print(Area)
x=pos_np[:,0]
y=pos_np[:,1]
i=np.arange(len(x))
Area=np.abs(np.sum((x[i-1])*(y[i])-(x[i])*(y[i-1]))*0.5)
print(Area+extra)