Skip to content

Instantly share code, notes, and snippets.

@0racle
Last active December 14, 2022 13:18
Show Gist options
  • Save 0racle/c1142c51df0471b57b51c8b31686760c to your computer and use it in GitHub Desktop.
Save 0racle/c1142c51df0471b57b51c8b31686760c to your computer and use it in GitHub Desktop.
Point example and AoC 2022-09
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
def __repr__(self):
return f"({self.x},{self.y})"
def __add__(p, q):
return Point(p.x + q.x, p.y + q.y)
from point import Point
from itertools import accumulate, chain
from math import copysign
def sign(n):
return 0 if n == 0 else int(copysign(1, n))
def step(h, t):
if abs(h.x - t.x) > 1 or abs(h.y - t.y) > 1:
return t + Point(sign(h.x - t.x), sign(h.y - t.y))
return t
def chains(xs, ys):
return chain.from_iterable([xs, ys])
def solve(path, length):
tail = [Point(0, 0)] * length
trail = set()
for h in path:
for i, (p, q) in enumerate(zip(chains([h], tail), tail)):
tail[i] = step(p, q)
trail.add(tail[-1])
return len(trail)
dirs = {
"U": Point(0, 1),
"R": Point(1, 0),
"D": Point(0, -1),
"L": Point(-1, 0),
}
points = []
for (d, c) in map(str.split, open("input").read().splitlines()):
points.extend([dirs[d]] * int(c))
path = list(accumulate(points))
print(solve(path, 1))
print(solve(path, 9))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment