advent-of-code/2019-python/output/day_08.py

51 lines
1 KiB
Python
Raw Normal View History

2023-11-23 14:49:48 +01:00
from collections import Counter
from textwrap import wrap
2023-12-19 18:34:03 +01:00
from output import answer
2023-11-23 14:49:48 +01:00
n = 8
title = "Space Image Format"
2023-12-19 18:34:03 +01:00
@answer(1, "The product of all 1s and 2s in the layer with fewest 0s is {}")
def part_1(o):
return o[0]
2023-11-23 14:49:48 +01:00
2023-12-19 18:34:03 +01:00
@answer(2, "The message is {}, the decoded image looks like above")
def part_2(o):
return o[1]
def solve(data):
2023-11-23 14:49:48 +01:00
layers = sorted(map(Counter, wrap(data, 25 * 6)), key=lambda c: c["0"])
2023-12-19 18:34:03 +01:00
width, height = 25, 6
2023-11-23 14:49:48 +01:00
a = layers[0]["1"]
b = layers[0]["2"]
2023-12-19 18:34:03 +01:00
p1 = a * b
2023-11-23 14:49:48 +01:00
layers = wrap(data, width * height)
pixels = zip(*layers)
lit = map(
lambda s: s.replace("0", ".").replace("1", "#"),
map(lambda p: next(filter(lambda x: x != "2", p)), pixels),
)
matrix = "\n".join(wrap("".join(lit), width))
2023-12-19 18:34:03 +01:00
print(matrix)
p2 = "CYUAH"
return p1, p2
2023-11-23 14:49:48 +01:00
if __name__ == "__main__":
2023-12-19 18:34:03 +01:00
with open("./input/08.txt", "r") as f:
inp = f.read().strip()
inp = solve(inp)
a = part_1(inp)
b = part_2(inp)
assert a == 2500
assert b == "CYUAH"