110 lines
1.9 KiB
Python
110 lines
1.9 KiB
Python
|
import fileinput
|
||
|
|
||
|
def make_matrix(rows, columns, default = False):
|
||
|
return [
|
||
|
[default for c in range(columns)] for r in range(rows)
|
||
|
]
|
||
|
|
||
|
def parse_input(lines):
|
||
|
X = []
|
||
|
Y = []
|
||
|
folds = []
|
||
|
for l in lines:
|
||
|
l = l.strip()
|
||
|
if l == '':
|
||
|
continue
|
||
|
if 'fold along' in l:
|
||
|
folds.append(
|
||
|
('x' if 'x' in l else 'y', int(l.split('=')[1]))
|
||
|
)
|
||
|
else:
|
||
|
c = list(map(int, l.split(',')))
|
||
|
X.append(c[0])
|
||
|
Y.append(c[1])
|
||
|
|
||
|
maxX, maxY = max(X), max(Y)
|
||
|
|
||
|
rows = make_matrix(maxY+1, maxX+1)
|
||
|
for x,y in zip(X, Y):
|
||
|
rows[y][x] = True
|
||
|
|
||
|
return X, Y, folds, rows
|
||
|
|
||
|
def draw_board(rows):
|
||
|
for r in rows:
|
||
|
line = ''
|
||
|
for c in r:
|
||
|
if not c:
|
||
|
line += '.'
|
||
|
else:
|
||
|
line += 'X'
|
||
|
print(line)
|
||
|
|
||
|
def merge_in(a, b):
|
||
|
new = []
|
||
|
for i in range(len(a)):
|
||
|
if a[i] or b[i]:
|
||
|
new.append(True)
|
||
|
else:
|
||
|
new.append(False)
|
||
|
return new
|
||
|
|
||
|
def get_column(rows, index):
|
||
|
out = []
|
||
|
for r in rows:
|
||
|
out.append(r[index])
|
||
|
return out
|
||
|
|
||
|
def set_column(rows, j, col):
|
||
|
out = rows.copy()
|
||
|
for i,c in enumerate(col):
|
||
|
out[i][j] = c
|
||
|
return out
|
||
|
|
||
|
|
||
|
def fold_along(rows, along, c):
|
||
|
print(f'fold {along=} {c=}')
|
||
|
new_rows = []
|
||
|
h = len(rows)
|
||
|
w = len(rows[0])
|
||
|
if along == 'y':
|
||
|
new_rows = make_matrix(c, w)
|
||
|
for i in range(0, c):
|
||
|
if i > 2*c-h:
|
||
|
new_rows[i] = (
|
||
|
merge_in(
|
||
|
rows[i],
|
||
|
rows[h-i-1]
|
||
|
)
|
||
|
)
|
||
|
if along == 'x':
|
||
|
new_rows = make_matrix(len(rows), c)
|
||
|
for j in range(0, c):
|
||
|
if j > 2*c-w:
|
||
|
new_rows = (
|
||
|
set_column(new_rows, j, merge_in(
|
||
|
get_column(rows, j),
|
||
|
get_column(rows, w-j-1)
|
||
|
))
|
||
|
)
|
||
|
return new_rows
|
||
|
|
||
|
def count_dots(rows):
|
||
|
count = 0
|
||
|
for r in rows:
|
||
|
for c in r:
|
||
|
if c: count += 1
|
||
|
return count
|
||
|
|
||
|
def main():
|
||
|
X, Y, folds, rows = parse_input(fileinput.input())
|
||
|
after_fold = rows.copy()
|
||
|
for along, c in folds:
|
||
|
after_fold = fold_along(after_fold, along, c)
|
||
|
count = count_dots(after_fold)
|
||
|
print(count)
|
||
|
|
||
|
draw_board(after_fold)
|
||
|
|
||
|
main()
|