63 lines
1.4 KiB
Python
63 lines
1.4 KiB
Python
|
#!/usr/bin/env python3
|
||
|
import fileinput
|
||
|
from pprint import pprint
|
||
|
from timeit import timeit
|
||
|
|
||
|
lines = list(fileinput.input())
|
||
|
|
||
|
|
||
|
def main():
|
||
|
h = 0
|
||
|
w = 0
|
||
|
|
||
|
dots = set()
|
||
|
folds = []
|
||
|
part1 = 0
|
||
|
for line in lines:
|
||
|
line = str(line)
|
||
|
if line[0].isdigit():
|
||
|
x, y = (int(n) for n in line.split(","))
|
||
|
h = max(x + 1, h)
|
||
|
w = max(y + 1, w)
|
||
|
dots.add((x, y))
|
||
|
elif line[0] == "f":
|
||
|
c, n = line.split("=")
|
||
|
folds.append((c[-1], int(n)))
|
||
|
|
||
|
for dir, pos in folds:
|
||
|
folded = set()
|
||
|
if dir == "y":
|
||
|
for x, y in dots:
|
||
|
if y > pos:
|
||
|
y2 = 2 * pos - y
|
||
|
folded.add((x, y2))
|
||
|
else:
|
||
|
folded.add((x, y))
|
||
|
else:
|
||
|
for x, y in dots:
|
||
|
if x > pos:
|
||
|
x2 = 2 * pos - x
|
||
|
folded.add((x2, y))
|
||
|
else:
|
||
|
folded.add((x, y))
|
||
|
dots = folded
|
||
|
|
||
|
if part1 == 0:
|
||
|
part1 = len(dots)
|
||
|
|
||
|
xs, ys = zip(*dots)
|
||
|
sheet = [[" "] * (max(xs) + 1) for _ in range(max(ys) + 1)]
|
||
|
for x, y in dots:
|
||
|
sheet[y][x] = "#"
|
||
|
|
||
|
return part1, ["".join(row).replace("#", "█") for row in sheet]
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
a, b = main()
|
||
|
print("part 1:", a)
|
||
|
print("part 2:")
|
||
|
print("\n".join(b))
|
||
|
|
||
|
print(f"{timeit(main, number=1000):.3f} ms")
|