2019 - Day 8 (Space Image Format)

View puzzle description on AdventOfCode.com
Part 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python3

#Advent of Code
#2019 Day 8, Part 1
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

def solve(puzzle_input):
    def parse_layer(data, width, height):
        return data[:width*height], data[width*height:]

    layers = []
    while len(puzzle_input) > 0:
        l, puzzle_input = parse_layer(puzzle_input, 25, 6)
        layers.append(l)
    layers.sort(key=lambda x: x.count("0"))

    return layers[0].count("1") * layers[0].count("2")

def main():
    puzzle_input = util.read.as_string()

    ones_by_twos = solve(puzzle_input)

    print("The the number of 1 digits multiplied by the number of 2 digits is " + str(ones_by_twos) + ".")

class AOC_Tests(unittest.TestCase):
    @unittest.skip("No test cases")
    def test_ex1(self):
        pass

if __name__ == "__main__":
    run(main)
Part 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python3

#Advent of Code
#2019 Day 8, Part 2
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

def solve(puzzle_input, width=25, height=6):
    def data_to_layers(data, width, height):
        layers = []
        while len(data) > 0:
            l, data = data[:width*height], data[width*height:]
            layers.append(l)
        return layers

    def combine_layers(vals):
        for v in vals:
            if v != "2":
                return v
        return "2"

    layers = data_to_layers(puzzle_input, width, height)
    
    image_data = []
    for i in range(len(layers[0])):
        image_data.append(combine_layers(x[i] for x in layers))
    
    return "".join(image_data)

def main():
    puzzle_input = util.read.as_string()

    image = solve(puzzle_input)

    print("The image is:")
    while len(image) > 0:
        l, image = image[:25], image[25:]
        print(l.replace("0", " ").replace("1", "*"))

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        self.assertEqual(solve("0222112222120000", 2, 2), "0110")

if __name__ == "__main__":
    run(main)
Return to solution index