advent-of-code/2021/python/day13.py

90 lines
2.5 KiB
Python
Raw Permalink Normal View History

2022-12-09 16:43:00 +00:00
import scanf
import itertools
import matrix
from matrix import ppmx as pmx
import numpy as np
import pandas as pd
import shared
from pprint import pprint as pp
class Oragami:
def __init__(self, name):
lines = []
with open(name, "r") as f:
for line in f.readlines():
lines.append(line.rstrip())
splitter = lines.index("")
coords, folds = lines[:splitter], lines[splitter + 1 :]
self.coords = [list(map(int, c.split(","))) for c in coords]
print(self.coords[:6])
self.parse_folds(folds)
self.max()
self.new_matrix()
def parse_folds(self, folds):
self.folds = []
for fold in folds:
axis, index = scanf.scanf("fold along %s=%d", fold)
self.folds.append({'axis':axis, 'index':index})
def max(self):
by_x = max([x['index'] for x in self.folds if x['axis'] == 'x'])
by_y = max([x['index'] for x in self.folds if x['axis'] == 'y'])
self.max_width = by_x*2+1
self.max_height = by_y*2+1
def new_matrix(self):
self.matrix = matrix.matrix_of_size(width=self.max_width, height=self.max_height)
for c, r in self.coords:
self.matrix[r][c] = 1
def process_folds(self):
for idx, fold in enumerate(self.folds):
print('---')
if fold['axis'] == 'y':
self.fold_y(fold['index'])
else:
self.fold_x(fold['index'])
self.count()
pmx(self.matrix,pad=False,space=False)
def fold_y(self, cut):
#folding on y removes the y row
bottom = self.matrix[cut+1:]
bottom = list(reversed(bottom))
self.matrix = self.matrix[:cut]
self.copy_from(bottom)
def fold_x(self, cut):
#folding on X removes the x column
left, right = [], []
removed = 0
for r, row in enumerate(self.matrix):
left.append(row[:cut])
right.append(list(reversed(row[cut+1:])))
if row[cut] == 1:
removed += 1
self.matrix = left
self.copy_from(right)
def copy_from(self, source):
for r, row in enumerate(source):
for c, col in enumerate(row):
if col == 1:
self.matrix[r][c] = 1
print("")
def count(self):
flat = np.ravel(np.array(self.matrix))
print(sum(flat))
def main():
o = Oragami(shared.get_fname(13))
o.process_folds()
if __name__ == "__main__":
main()