-
Notifications
You must be signed in to change notification settings - Fork 0
/
day8.py
77 lines (58 loc) · 1.88 KB
/
day8.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# vi: set shiftwidth=4 tabstop=4 expandtab:
import datetime
import os
import itertools
top_dir = os.path.dirname(os.path.abspath(__file__)) + "/../../"
def get_image_from_file(file_path=top_dir + "resources/year2019_day8_input.txt"):
with open(file_path) as f:
return [l.strip() for l in f][0]
def grouper(iterable, n, fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return itertools.zip_longest(*args, fillvalue=fillvalue)
def get_layers(image, width, height):
dim = width * height
return grouper(image, dim)
def find_number1(image, width, height):
layers = list(get_layers(image, width, height))
layer = min(layers, key=lambda s: s.count("0"))
return layer.count("1") * layer.count("2")
def get_pixel(index, layers):
transparent = "2"
for l in layers:
v = l[index]
if v != transparent:
return v
assert False
def get_image(image, width, height):
layers = list(get_layers(image, width, height))
pixels = "".join(get_pixel(i, layers) for i in range(len(layers[0])))
return "\n".join("".join(line) for line in grouper(pixels, width))
def run_tests():
image = "0222112222120000"
assert (
get_image(image, 2, 2)
== """01
10"""
)
def get_solutions():
image = get_image_from_file()
width, height = 25, 6
print(find_number1(image, width, height) == 2032)
print(
get_image(image, width, height).replace("0", " ")
== """\
11 1111 11 1 1 11
1 1 1 1 1 1 1 1 1
1 111 1 1 1 1
1 1 1 1 1 1 11
1 1 1 1 1 1 1 1 1
11 1 11 11 111 """
)
if __name__ == "__main__":
begin = datetime.datetime.now()
run_tests()
get_solutions()
end = datetime.datetime.now()
print(end - begin)