Created
December 13, 2021 15:29
-
-
Save leeacto/10c7bd4293130a9401286d7d73a27ffe to your computer and use it in GitHub Desktop.
day13pt2.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| filename = '13.txt' | |
| class Grid(): | |
| def __init__(self, max_x, max_y, coords, folds): | |
| self.max_x = max_x | |
| self.max_y = max_y | |
| self.coords = coords | |
| self.folds = folds | |
| self.map = None | |
| self.build_map() | |
| def __repr__(self): | |
| return '\n'.join([''.join(r) for r in self.map]) | |
| def build_map(self): | |
| template = [ | |
| ['.' for _ in range(self.max_x + 1)] | |
| for _ in range(self.max_y + 1)] | |
| for coord in coords: | |
| template[coord[1]][coord[0]] = '#' | |
| self.map = template | |
| def fold_all(self): | |
| while self.folds: | |
| self.fold() | |
| def fold(self): | |
| letter, num = self.folds.pop(0) | |
| if letter == 'x': | |
| self.fold_left(num) | |
| else: | |
| self.fold_up(num) | |
| def fold_up(self, fold_row): | |
| top_half = self.map[:fold_row] | |
| bottom_half = list(reversed(self.map[fold_row:])) | |
| new_map = [] | |
| for i in range(fold_row): | |
| new_row = [ | |
| '#' if '#' in [top_half[i][j], bottom_half[i][j]] else '.' | |
| for j in range(len(top_half[i])) | |
| ] | |
| new_map.append(new_row) | |
| self.map = new_map | |
| def fold_left(self, fold_col): | |
| new_map = [] | |
| for row in self.map: | |
| left_half = row[:fold_col] | |
| right_half = list(reversed(row[fold_col:])) | |
| new_row = ['#' if '#' in [left_half[i], right_half[i]] else '.' | |
| for i in range(len(left_half))] | |
| new_map.append(new_row) | |
| self.map = new_map | |
| def count_dots(self): | |
| dots = 0 | |
| for row in self.map: | |
| for c in row: | |
| dots += 1 if c == '#' else 0 | |
| return dots | |
| coords = [] | |
| folds = [] | |
| max_x = 0 | |
| max_y = 0 | |
| with open(filename, 'r') as f: | |
| for line in f: | |
| if ',' in line: | |
| new_coord = [int(n) for n in line.strip().split(',')] | |
| max_x = max(max_x, new_coord[0]) | |
| max_y = max(max_y, new_coord[1]) | |
| coords.append(new_coord) | |
| elif 'fold' in line: | |
| directions = line.strip().split('=') | |
| folds.append((directions[0][-1], int(directions[1]))) | |
| grid = Grid(max_x, max_y, coords, folds) | |
| grid.fold_all() | |
| print(grid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment