Solution to problem 8 in Python

This commit is contained in:
David Doblas Jiménez 2022-04-09 19:17:15 +02:00
parent 70cd64d55b
commit 46d51b8548
1 changed files with 73 additions and 0 deletions

View File

@ -62,5 +62,78 @@ def part_1() -> None:
print(f"The result is {layer[1] * layer[2]}")
# --- Part Two ---
# Now you're ready to decode the image. The image is rendered by stacking the
# layers and aligning the pixels with the same positions in each layer. The
# digits indicate the color of the corresponding pixel: 0 is black, 1 is white,
# and 2 is transparent.
# The layers are rendered with the first layer in front and the last layer in
# back. So, if a given position has a transparent pixel in the first and second
# layers, a black pixel in the third layer, and a white pixel in the fourth
# layer, the final image would have a black pixel at that position.
# For example, given an image 2 pixels wide and 2 pixels tall, the image data
# 0222112222120000 corresponds to the following image layers:
# Layer 1: 02
# 22
# Layer 2: 11
# 22
# Layer 3: 22
# 12
# Layer 4: 00
# 00
# Then, the full image can be found by determining the top visible pixel in
# each position:
# The top-left pixel is black because the top layer is 0.
# The top-right pixel is white because the top layer is 2 (transparent),
# but the second layer is 1.
# The bottom-left pixel is white because the top two layers are 2, but the
# third layer is 1.
# The bottom-right pixel is black because the only visible pixel in that
# position is 0 (from layer 4).
# So, the final image looks like this:
# 01
# 10
# What message is produced after decoding your image?
def part_2() -> None:
picture_size = 25 * 6
layers = []
for i in range(0, len(digits), picture_size):
layer = digits[i : i + picture_size]
layers.append(layer)
full_image = []
for pixel in range(picture_size):
for layer in layers:
if layer[pixel] == 2:
continue
full_image.append(layer[pixel])
break
for idx, pixel in enumerate(full_image):
if pixel == 0:
print(" ", end="")
elif pixel == 1:
print("X", end="")
elif pixel == 2:
print("o", end="")
if (idx + 1) % 25 == 0:
print()
if __name__ == "__main__":
part_1()
part_2()