Added 2025 day9

This commit is contained in:
2025-12-09 21:00:07 +01:00
parent 911eaad03a
commit 831a91d92b
3 changed files with 96 additions and 3 deletions
+86
View File
@@ -0,0 +1,86 @@
#!/bin/python3
import sys,time,re,os,copy
from pprint import pprint
sys.path.insert(0, '../../')
from fred import *
start_time = time.time()
if sys.argv[1] == 'test':
input_f = 'test'
elif sys.argv[1] == 'input':
input_f = 'input'
else:
print('No argv provided')
exit()
#########################################
# #
# Part 1 #
# #
#########################################
def area(cords1,cords2):
width = abs(cords1[0]-cords2[0])+1
height = abs(cords1[1]-cords2[1])+1
return width*height
def part1():
score = 0
lines = loadFile(input_f,',')
heap = []
for i in range(len(lines)):
for j in range(i+1,len(lines)):
cords1 = (list2int(lines[i]))
cords2 = (list2int(lines[j]))
a = area(cords1,cords2)
heapq.heappush(heap, (a,cords1,cords2)) #only needed for part 2
if a > score:
score = a
return score,heap # heap only for part 2
start_time = time.time()
p1,heap = part1()
print('Part 1:',p1, '\t\t', round((time.time() - start_time)*1000), 'ms')
#########################################
# #
# Part 2 #
# #
#########################################
def part2(heap):
from shapely.geometry import Polygon, box
lines = loadFile(input_f,',')
for l in range(len(lines)):
lines[l] = tuple(list2int(lines[l]))
shape = Polygon(lines)
heapq._heapify_max(heap)
score = 0
while heap:
area,cords1,cords2 = heapq._heappop_max(heap)
x1,y1 = cords1
x2,y2 = cords2
rect = box(min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
if shape.contains(rect):
score = area
break
return score
start_time = time.time()
p2 = part2(heap)
print('Part 2:',p2, '', round((time.time() - start_time)*1000), 'ms')
+3
View File
@@ -20,6 +20,9 @@
|&%;]__[]_[]_[]__<>| | |H_/|\ \\\\\\ | | | 7 **
'...|<>__|H__|_\__|_____|_[_O_|
| 8 **
/ ______ __ | _________________O__
[ |(__) [ ] \ |__| [ ] '''''' | | 9 **
## 2024
.-----. .------------------.
+6 -2
View File
@@ -13,12 +13,13 @@ def findInGrid(grid:list,x:str) -> set:
if char == x:
return (r,c)
def loadFile(input_f):
def loadFile(input_f, s:str=None):
"""
Loads a file and returns its lines as a list.
Args:
input_f (str): The file path to read from.
s (str, optional): Delimiter to split lines by. Defaults to None.
Returns:
list: A list of lines from the file, with each line stripped of trailing newlines.
@@ -31,7 +32,10 @@ def loadFile(input_f):
try:
with open(input_f) as file:
for line in file:
lines.append(line.rstrip()) # Removes trailing newline from each line
if s == None:
lines.append(line.rstrip()) # Removes trailing newline from each line
else:
lines.append(line.rstrip().split(s))
except FileNotFoundError:
raise FileNotFoundError(f"The file '{input_f}' was not found.")
except IOError as e: