#!/usr/bin/env python # 2021 - Advent Of Code - 13 part 2 # 2022: cheat for pylint to start fresh for 2022 # pylint: disable=unnecessary-list-index-lookup def parse_file(file): parsed_dots = [] parsed_folds = [] with open(file, encoding="utf-8") as f: for line in f.readlines(): if line.startswith('fold along '): _, f = line.strip().split('fold along ') parsed_folds.append(f.split('=')) elif line == '\n': pass else: dot = [int(d) for d in line.strip().split(',')] parsed_dots.append(dot) return parsed_dots, parsed_folds def find_max(dot_list): mx = 0 my = 0 for d in dot_list: if d[0] > mx: mx = d[0] if d[1] > my: my = d[1] return mx, my def place_dots(g, dots_list): for dot in dots_list: g[dot[1]][dot[0]] = 1 def print_grid(g): for y, _ in enumerate(g): for x, _ in enumerate(g[y]): if g[y][x] == 1: print('#', end='') else: print('.', end='') print() def fold_horizontally(g, fold_y, g_maxy): print(f'folding y={fold_y}') for y in range(fold_y, g_maxy+1): folding_dist = y - fold_y new_y = fold_y - folding_dist # place new dots for x, _ in enumerate(g[y]): if g[y][x] == 1: g[new_y][x] = 1 # cut the other half of the grid for _ in range(fold_y+1): g.pop() return fold_y-1 def fold_vertically(g, fold_x, g_maxx): print(f'folding x={fold_x}') for y, _ in enumerate(g): # place new dots for x in range(fold_x, g_maxx+1): folding_dist = x - fold_x new_x = fold_x - folding_dist if g[y][x] == 1: g[y][new_x] = 1 # cut the other half of the grid g[y] = g[y][:fold_x] return fold_x-1 def count_dots(g): count = 0 for y, _ in enumerate(g): for x, _ in enumerate(g[y]): if g[y][x] == 1: count += 1 return count # dots, folds = parse_file('input_example.txt') dots, folds = parse_file('input.txt') maxx, maxy = find_max(dots) grid = [[0] * (maxx+1) for _ in range(maxy+1)] place_dots(grid, dots) print(f'grid size: {maxx}, {maxy}') print(f'real grid size: {len(grid[0])}, {len(grid)}') print() for fold in folds: if fold[0] == 'x': maxx = fold_vertically(grid, int(fold[1]), maxx) else: maxy = fold_horizontally(grid, int(fold[1]), maxy) print(f'grid size: {maxx}, {maxy}') print(f'real grid size: {len(grid[0])}, {len(grid)}') print() print_grid(grid)