-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_11.py
95 lines (75 loc) · 2.7 KB
/
day_11.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def parse():
with open("input.txt", "r") as fp:
return [[int(i) for i in j if i != '\n'] for j in fp.readlines()]
class Octopus():
def __init__(self, energy):
self.energy = energy
self.can_flash = True
def __str__(self):
return str(self.energy)
def increment(self):
if self.can_flash:
if self.energy < 9:
self.energy += 1
return False
else:
self.energy = 0
self.can_flash = False
return True
def reset(self):
self.can_flash = True
class Octopi():
def __init__(self, levels):
self.map = [[Octopus(i) for i in j] for j in levels]
def __str__(self):
return "\n".join(["".join([str(i) for i in j]) for j in self.map])
def reset(self):
for i in self.map:
for j in i:
j.reset()
def flash(self, x, y):
result = 1
if x > 0:
if self.map[y][x-1].increment():
result += self.flash(x-1, y)
if x < len(self.map[y])-1:
if self.map[y][x+1].increment():
result += self.flash(x+1, y)
if y > 0:
if self.map[y-1][x].increment():
result += self.flash(x, y-1)
if y < len(self.map)-1:
if self.map[y+1][x].increment():
result += self.flash(x, y+1)
if x > 0:
if y > 0:
if self.map[y-1][x-1].increment():
result += self.flash(x-1, y-1)
if y < len(self.map)-1:
if self.map[y+1][x-1].increment():
result += self.flash(x-1, y+1)
if x < len(self.map[y])-1:
if y > 0:
if self.map[y-1][x+1].increment():
result += self.flash(x+1, y-1)
if y < len(self.map)-1:
if self.map[y+1][x+1].increment():
result += self.flash(x+1, y+1)
return result
def increment(self, steps=1):
result = 0
for step in range(steps):
self.reset()
for y in range(len(self.map)):
for x in range(len(self.map[y])):
if self.map[y][x].increment():
result += self.flash(x, y)
return result
def synchronize(self):
result = 0
while (sum([sum([i.energy for i in j]) for j in self.map])) > 0:
self.increment()
result += 1
return result
print(Octopi(parse()).increment(100))
print(Octopi(parse()).synchronize())