adventofcode-2021/13/solve02.py

63 lines
1.3 KiB
Python
Raw Normal View History

2021-12-13 07:27:17 +01:00
#!/usr/bin/env python
import re
import copy
from collections import defaultdict
dots = dict()
folds = []
def do_fold_x(dots, line):
copy_dots = copy.copy(dots)
for dot in dots:
x = dot[0]
if x <= line:
continue
x1 = line - (x - line)
copy_dots[(x1, dot[1])] = True
del copy_dots[dot]
return copy_dots
def do_fold_y(dots, line):
copy_dots = copy.copy(dots)
for dot in dots:
y = dot[1]
if y <= line:
continue
y1 = line - (y - line)
copy_dots[(dot[0], y1)] = True
del copy_dots[dot]
return copy_dots
def print_dots(dots):
max_x = max([x for (x,y) in dots.keys()])
max_y = max([y for (x,y) in dots.keys()])
for py in range(max_y+1):
px = [x for (x,y) in dots.keys() if y == py]
line = [' ']*(max_x+1)
for i in px:
line[i] = '*'
print(''.join(line))
RE_FOLD = re.compile("fold along ([xy])=(\d+)$")
with open("input01.txt","r") as f:
for line in f:
line = line.strip()
if len(line) == 0:
break
tmp = line.split(",",2)
dots[(int(tmp[0]), int(tmp[1]))] = True
for line in f:
line = line.strip()
if len(line) == 0:
break
m = RE_FOLD.match(line)
folds.append((m.group(1), int(m.group(2))))
for f in folds:
if f[0] == 'x':
dots = do_fold_x(dots, f[1])
if f[0] == 'y':
dots = do_fold_y(dots, f[1])
print_dots(dots)