Skip to content

Instantly share code, notes, and snippets.

@mlesniew
Created December 13, 2021 20:29
Show Gist options
  • Save mlesniew/3ad498da58a8c6904df66224f33e7e89 to your computer and use it in GitHub Desktop.
Save mlesniew/3ad498da58a8c6904df66224f33e7e89 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import sys
import re
points = set()
folds = []
for line in sys.stdin:
line = line.strip()
if not line:
continue
elif match := re.match("([0-9]+),([0-9]+)", line):
point = tuple(int(c) for c in match.groups())
points.add(point)
elif match := re.match("fold along ([xy])=([0-9]+)", line):
fold = match.groups()
folds.append((fold[0], int(fold[1])))
else:
assert False, "Syntax error"
def transpose(points):
return set((y, x) for x, y in points)
def fold_y(points, z):
above = set(p for p in points if p[1] < z)
below = set(p for p in points if p[1] > z)
for x, y in below:
point = (x, z - (y - z))
above.add(point)
return above
def fold_x(points, z):
return transpose(fold_y(transpose(points), z))
def fold(points, axis, z):
return (fold_x if axis == "x" else fold_y)(points, z)
def show(points):
w = max(p[0] for p in points) + 1
h = max(p[1] for p in points) + 1
for y in range(h):
print("".join("#" if (x, y) in points else "." for x in range(w)))
for n, (axis, z) in enumerate(folds):
points = fold(points, axis, z)
if not n:
print("Part 1:", len(points))
print("Part 2:")
show(points)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment