Advertisement
usesbiggerwords

AoC Day 13

Dec 15th, 2021
447
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. from collections import defaultdict
  2. from typing import List, DefaultDict, Tuple
  3. import os
  4.  
  5.  
  6. def read_and_init(fn) -> Tuple[DefaultDict[complex, int], List[complex], List[str]]:
  7.     dots = []
  8.     folds = []
  9.     paper = defaultdict(int)
  10.     with open(fn, 'r') as fo:
  11.         lines = fo.read().splitlines()
  12.     for line in lines:
  13.         if line:
  14.             if 'fold' in line:
  15.                 folds.append(line.split()[2])
  16.             else:
  17.                 x, y = list(map(int, line.split(',')))
  18.                 dots.append(x+1j*y)
  19.     return paper, dots, folds
  20.  
  21.  
  22. def transform(paper: DefaultDict[complex, int], fold: str) -> DefaultDict[complex, int]:
  23.     axis, val = fold.split('=')
  24.     new_paper = defaultdict(int)
  25.     if axis == 'x':
  26.         # vertical fold
  27.         x_max = int(val)
  28.         y_max = int(max(key.imag for key in paper))
  29.         for y in range(y_max + 1):
  30.             for x in range(x_max):
  31.                 loc = x+1j*y
  32.                 mirror_loc = (2*x_max-x)+1j*y
  33.                 new_paper[loc] = paper[loc] | paper[mirror_loc]
  34.     else:
  35.         # horizontal fold
  36.         y_max = int(val)
  37.         x_max = int(max(key.real for key in paper))
  38.         for y in range(y_max):
  39.             for x in range(x_max + 1):
  40.                 loc = x+1j*y
  41.                 mirror_loc = x+1j*(2*y_max-y)
  42.                 new_paper[loc] = paper[loc] | paper[mirror_loc]
  43.     return new_paper
  44.  
  45.  
  46. def part1(paper: DefaultDict[complex, int], dots: List[complex], folds: List[str]):
  47.     for dot in dots:
  48.         paper[dot] = 1
  49.     fold = folds[0]
  50.     paper = transform(paper, fold)
  51.     return sum(paper.values())
  52.  
  53.  
  54. def part2(paper: DefaultDict[complex, int], dots: List[complex], folds: List[str]):
  55.     for dot in dots:
  56.         paper[dot] = 1
  57.     for fold in folds:
  58.         paper = transform(paper, fold)
  59.     display = []
  60.     for y in range(int(max(k.imag for k in paper)) + 1):
  61.         line = []
  62.         for x in range(int(max(k.real for k in paper)) + 1):
  63.             if paper[x+1j*y]:
  64.                 line.append('#')
  65.             else:
  66.                 line.append(' ')
  67.         display.append(''.join(line))
  68.     for line in display:
  69.         print(line)
  70.  
  71.  
  72. p, d, f = read_and_init(os.path.dirname(__file__) + '\\in.txt')
  73. result = part1(p, d, f)
  74. print('Part 1:', result)
  75. part2(p, d, f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement