AdventOfCode/2023/day18/part1.py

147 lines
2.6 KiB
Python

import sys
import os
from pprint import pprint
import time
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import shapely
import numpy as np
from matplotlib.path import Path
import sympy
#colors
from termcolor import colored
def p(x,inside):
for idx,i in enumerate(x):
for jdx,j in enumerate(i):
#if j == '#':
# print(colored(j,'red'),end='')
#if (idx,jdx) in steps:
# print(colored(j,'blue'),end='')
if (idx,jdx) in inside:
print(colored(j,'green'),end='')
else:
print(j,end='')
print()
input_f = ''
if len(sys.argv) == 1:
input_f = 'test'
else:
input_f = sys.argv[1]
grid = []
with open(input_f) as file:
for line in file:
grid.append(line.rstrip().split())
pprint(grid)
size = 20
pit = [ ['.']*size for i in range(size)]
cur = (int(size/2),int(size/2))
#p(pit)
print()
steps = []
for i in grid:
direction,length,color = i
#print(cur)
length = int(length)
#print(direction,length)
if direction == 'R':
for x in range(cur[1],cur[1]+length+1):
pit[cur[0]][x] = '#'
steps.append((cur[0],x))
#print(cur[0],x)
cur = (cur[0],cur[1]+length)
if direction == 'D':
for x in range(cur[0],cur[0]+length):
pit[x][cur[1]] = '#'
steps.append((x,cur[1]))
# print(x,cur[1])
cur = (cur[0]+length,cur[1])
if direction == 'L':
for x in range(cur[1],cur[1]-length-1,-1):
pit[cur[0]][x] = '#'
steps.append((cur[0],x))
# print(cur[0],x)
cur = (cur[0],cur[1]-length)
if direction == 'U':
for x in range(cur[0],cur[0]-length,-1):
pit[x][cur[1]] = '#'
steps.append((x,cur[1]))
# print(x,cur[1])
cur = (cur[0]-length,cur[1])
#print(steps)
#p(pit,(0,0))
#input()
#pprint(steps)
ground = []
path = Path(steps)
s_ground = []
m_ground = []
polygon = Polygon(steps)
count = 0
for ydx,y in enumerate(pit):
for xdx,x in enumerate(y):
if path.contains_point((ydx,xdx)):
m_ground.append((ydx,xdx))
if polygon.contains(Point(ydx,xdx)):
s_ground.append((ydx,xdx))
#p(pit,s_ground)
# pprint(len(s_ground))
# pprint(len(m_ground))
# print(len(m_ground)+len(set(steps)))
# print('Part 1: ' + str(len(set(steps))))
# print('Part 1.2: ' + str(len(s_ground)+len(set(steps))))
# print(len(ground) + len(set(steps)))
# p(pit,s_ground)
# print(len(s_ground))
# p(pit,m_ground)
# print(len(m_ground))
#print('Part 1: ',end='')
#print(area(polygon))
#print(len(m_ground))
print('Part 1.2: ' + str(shapely.area(polygon)))
# 57559
# 58612
# 62918
# Part 1: 4306
# Part 1.2: 61865 //corrent
# 4306