adventofcode2024/day14/sol.py

57 lines
1.3 KiB
Python
Raw Normal View History

2024-12-14 05:19:02 +00:00
import re
def parse(file):
robots = []
for line in file:
match = re.findall(r'-?\d+', line)
px,py, vx,vy = [int(x) for x in match]
robots.append(((px,py),(vx,vy)))
return robots
def solve(file, W, H):
robots = parse(file)
2024-12-14 06:07:28 +00:00
#print(robots)
2024-12-14 05:19:02 +00:00
2024-12-14 06:07:28 +00:00
robots100 = [iterate(r, 100, W, H) for r in robots]
#print(robots100)
2024-12-14 05:19:02 +00:00
2024-12-14 06:07:28 +00:00
q = quad_score(robots100, W, H)
print(q)
2024-12-14 05:19:02 +00:00
2024-12-14 06:07:28 +00:00
minq = float('inf')
mint = 0
2024-12-14 06:00:19 +00:00
for t in range(0, W*H):
2024-12-14 06:07:28 +00:00
rs = (iterate(r, t, W, H) for r in robots)
q = quad_score(rs, W, H)
if minq > q:
minq = q
mint = t
picture = [["."]*W for _ in range(H)]
for r in robots:
(x,y),_ = iterate(r, mint, W, H)
picture[y][x] = "#"
for line in picture:
print("".join(line))
print("t = ", mint, "q = ", minq)
def quad_score(robots, W, H):
2024-12-14 06:00:19 +00:00
mx = W//2
my = H//2
q1, q2, q3, q4 = 0, 0, 0, 0
for (x,y),_ in robots:
if x < mx and y < my: q1 += 1
if x > mx and y < my: q2 += 1
if x < mx and y > my: q3 += 1
if x > mx and y > my: q4 += 1
2024-12-14 06:07:28 +00:00
return q1*q2*q3*q4
2024-12-14 06:00:19 +00:00
2024-12-14 05:19:02 +00:00
def iterate(robot, t, W, H):
(px,py), (vx,vy) = robot
px = (px+vx*t)%W
py = (py+vy*t)%H
return (px,py), (vx,vy)
2024-12-14 06:07:28 +00:00
solve(open("sample1.in"), 11, 7)
solve(open("input"), 101, 103)