advent_of_code/2023/day18/part_two.py

72 lines
1.8 KiB
Python
Raw Permalink Normal View History

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 = {2: [-1,0], 0: [1,0], 3: [0,-1], 1: [0,1]}
adders = {2: 0, 0: 0, 3: 0, 1: 0}
extra = 1
def polygon_area(points):
"""Return the area of the polygon whose vertices are given by the
sequence points.
"""
area = 0
q = points[-1]
for p in points:
area += (p[0] * q[1] - p[1] * q[0])/2
q = p
return area
# 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)
turtle.setpos(*current_pos)
for line in lines:
parts = line.split(" ")
color_raw = parts[2].strip("(#)")
new_dir = dir[int(color_raw[-1])]
mult = int(color_raw[0:-1], 16)
# adder = 0 if int(color_raw[-1]) <= 1 else 1
adder = adders[int(color_raw[-1])]
current_pos = [current_pos[0] + (mult+adder)*new_dir[0], current_pos[1] + (mult+adder)*new_dir[1]]
if int(color_raw[-1]) == 0 or int(color_raw[-1]) == 3:
extra += int(color_raw[0:-1], 16)
positions.append(current_pos)
print(current_pos)
color_array = []
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, dtype = np.float64)
# pos_np = pos_np-np.array([np.min(pos_np[:,0]), np.min(pos_np[:,1])])
print(polygon_area(pos_np))
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)
w = np.max(pos_np[:,0]) - np.min(pos_np[:,0])
h = np.max(pos_np[:,1]) - np.min(pos_np[:,1])
print(Area+extra)