Skip to content

Instantly share code, notes, and snippets.

@rodrigogiraoserrao
Created December 17, 2024 18:54
Show Gist options
  • Save rodrigogiraoserrao/6602cee9f05b1b12f1950b10379594a4 to your computer and use it in GitHub Desktop.
Save rodrigogiraoserrao/6602cee9f05b1b12f1950b10379594a4 to your computer and use it in GitHub Desktop.
# === Parsing ===
import re
LINE_RE = re.compile(r"p=(\d+),(\d+) v=(-?\d+),(-?\d+)")
WIDTH = 101
HEIGHT = 103
robots = []
with open("input.txt", "r") as f:
for line in f:
px, py, vx, vy = map(int, LINE_RE.match(line).groups())
robots.append(((px, py), (vx, vy)))
print(robots[0])
# === Part 1 ===
from collections import Counter
from math import prod
def move(pos, velocity, steps):
px, py = pos
vx, vy = velocity
return (
(px + steps * vx) % WIDTH,
(py + steps * vy) % HEIGHT,
)
final_robots = [move(pos, vel, 100) for pos, vel in robots]
print(
prod(
Counter(
(px < WIDTH / 2, py < HEIGHT / 2) # Encode the quadrant.
for px, py in final_robots
if px != WIDTH // 2 and py != HEIGHT // 2
).values()
)
)
# === Part 2 ===
from PIL import Image
def print_robots(robots):
for y in range(HEIGHT):
for x in range(WIDTH):
if (x, y) in robots:
print("#", end="")
else:
print(" ", end="")
print()
def make_frame(robots):
image = Image.new("L", (WIDTH, HEIGHT), "black")
pixels = image.load()
for x, y in robots:
pixels[x, y] = 255
return image
for steps in range(7056):
moved_robots = {move(pos, vel, steps) for pos, vel in robots}
frame = make_frame(moved_robots)
# frame.save(f"frames/frame{steps:04}.png")
print(7055)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment