Created
December 8, 2019 06:27
-
-
Save mattmess1221/6bcff233d11fd64637c5134fba6a1168 to your computer and use it in GitHub Desktop.
This file contains 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
from typing import List | |
import aoc | |
def read_layers(data: List[int], width: int, height: int): | |
size = width * height | |
for layer in range(len(data) // size): | |
yield Layer(data[size * layer:size * (layer + 1)], width, height) | |
class Layer: | |
def __init__(self, pixels: List[int], width: int, height: int): | |
self.pixels = pixels | |
self.width = width | |
self.height = height | |
self.__iter__ = self.pixels.__iter__ | |
def render(self): | |
rows = [] | |
for row in range(self.height): | |
rows.append(''.join(map(str, self.pixels[row * self.width:(row + 1) * self.width]))) | |
return '\n'.join(rows).replace('0', ' ').replace('1', '\u2588') | |
class Image: | |
def __init__(self, pixels: List[int], width: int, height: int): | |
self.layers = list(read_layers(pixels, width, height)) | |
self.width = width | |
self.height = height | |
def merge(self): | |
image = self.layers[0].pixels.copy() | |
for layer in self.layers[1:]: | |
for i, pixel in enumerate(layer.pixels): | |
if image[i] == 2: | |
image[i] = pixel | |
return Layer(image, self.width, self.height) | |
def main(): | |
with aoc.open_input(__name__) as f: | |
data = [int(i) for i in f.read()] | |
image = Image(data, 25, 6) | |
print(calculate(image)) | |
print(image.merge().render()) | |
def test(): | |
data = [int(i) for i in '123456789012'] | |
image = Image(data, 3, 2) | |
print(calculate(image)) | |
data = [int(i) for i in '0222112222120000'] | |
image = Image(data, 2, 2) | |
print(image.merge().render()) | |
def calculate(image: Image) -> int: | |
layer = min(image.layers, key=lambda l: l.pixels.count(0)) | |
num_1s = layer.pixels.count(1) | |
num_2s = layer.pixels.count(2) | |
return num_1s * num_2s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment