SHARE
TWEET

Untitled

a guest Dec 8th, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from typing import Text, List, Dict, Iterable
  2. from collections import Counter
  3.  
  4.  
  5. class Layers(object):
  6.  
  7.     def __init__(self, width: int, height: int, data: List[int]):
  8.         self.layers = []
  9.         self.width = width
  10.         self.height = height
  11.         self.parse_encoded_data(data)
  12.  
  13.     def parse_encoded_data(self, data: List[int]):
  14.         lines = [data[i:i+self.width] for i in range(0, len(data), self.width)]
  15.         assert len(lines) % self.height == 0
  16.         [self.layers.append(lines[i:i+self.height]) for i in range(0, len(lines), self.height)]
  17.  
  18.     def generate_histograms(self) -> Iterable[Dict[int, int]]:
  19.         """Get a histogram of pixel values per layer."""
  20.         for layer in self.layers:
  21.             yield Counter([x for y in layer for x in y])
  22.  
  23.     def find_part_1(self):
  24.         least_zeros = min(self.generate_histograms(), key=lambda x: x.get(0, 0))
  25.         return least_zeros.get(1) * least_zeros.get(2)
  26.  
  27.     def decode_image(self):
  28.         if not self.layers:
  29.             return
  30.         final_image = self.layers[0]
  31.         for layer in self.layers[1:]:
  32.             final_image = [[a if a != 2 else b for a, b in zip(x, y)] for x, y in zip(final_image, layer)]
  33.         return final_image
  34.  
  35. def main():
  36.     pixels = open("day8.data").readlines()[0].strip()
  37.     layers = Layers(25, 6, [int(x) for x in pixels])
  38.  
  39.     print(layers.find_part_1())
  40.     for x in layers.decode_image():
  41.         print("".join(["X" if y else " " for y in x]))
  42.  
  43.  
  44. if __name__ == '__main__':
  45.     main()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top