Advertisement
illuminati229

AoC Day 20

Dec 20th, 2021 (edited)
578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import numpy as np
  2. from time import perf_counter
  3.  
  4. def scanner_enhance(file_path, max_run):
  5.  
  6.     with open(file_path) as fin:
  7.         algo, image = fin.read().strip().split('\n\n')
  8.  
  9.     algo_b = {}
  10.  
  11.     for i, val in enumerate(algo):
  12.         if val == '#':
  13.             algo_b[i] = 1
  14.         else:
  15.             algo_b[i] = 0
  16.  
  17.     image = image.split('\n')
  18.     image_b = np.zeros((len(image), len(image[0])), dtype=int)
  19.  
  20.     for i, row in enumerate(image):
  21.         for j, val in enumerate(row):
  22.             if val == '#':
  23.                 image_b[i,j] = 1
  24.             else:
  25.                 image_b[i,j] = 0
  26.  
  27.     run = 1
  28.  
  29.     while run <= max_run:
  30.         if algo_b[1] == 1 and not run % 2:
  31.             image_pad = np.ones((image_b.shape[0] + 4,
  32.                                  image_b.shape[1] + 4),
  33.                                 dtype=int)
  34.         else:
  35.             image_pad = np.zeros((image_b.shape[0] + 4,
  36.                                   image_b.shape[1] + 4),
  37.                                  dtype=int)
  38.  
  39.         image_pad[2:-2,2:-2] = image_b
  40.  
  41.         e_image = np.zeros((image_b.shape[0] + 2,
  42.                             image_b.shape[1] + 2),
  43.                            dtype=int)
  44.  
  45.         for loc, val in np.ndenumerate(image_pad):
  46.             x, y = loc
  47.             if (x in range(1, len(image_pad) - 1)
  48.                 and y in range(1, len(image_pad) - 1)):
  49.                 sub_pix = image_pad[x-1:x+2, y-1:y+2]
  50.                 pix_str = ''
  51.                 for row in sub_pix:
  52.                     for s_val in row:
  53.                         pix_str += str(s_val)
  54.  
  55.                 e_image[x-1, y-1] = algo_b[int(pix_str, 2)]
  56.        
  57.         image_b = e_image.copy()
  58.         run += 1
  59.        
  60.     return np.count_nonzero(image_b)
  61.  
  62. def main():
  63.  
  64.     assert scanner_enhance('test_input.txt', 2) == 35
  65.     print(scanner_enhance('input.txt', 2))
  66.  
  67.     assert scanner_enhance('test_input.txt', 50) == 3351
  68.     start = perf_counter()
  69.     print(scanner_enhance('input.txt', 50), perf_counter() - start)
  70.  
  71. if __name__ == '__main__':
  72.     main()
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement