-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
80 lines (64 loc) · 2.37 KB
/
main.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
class Day11:
def __init__(self):
self.puzzle_input = self.get_puzzle_input()
self.row_length = len(self.puzzle_input[0]) - 1
self.column_length = len(self.puzzle_input) - 1
self.flashes = 0
def part_one(self) -> int:
return self.simulate_octopuses(steps=100)
def part_two(self) -> int:
return self.simulate_octopuses(steps=9999)
def simulate_octopuses(self, steps) -> int:
data = self.puzzle_input.copy()
for i in range(steps):
for index, line in enumerate(data):
data[index] = [int(x)+1 for x in line]
for x, line in enumerate(data):
for y, number in enumerate(line):
if number > 9:
data[x][y] = 0
self.flashes += 1
self.increase_adjacent(data, x, y)
if self.is_all_flashing(data):
return i + 1
return self.flashes
@staticmethod
def is_all_flashing(data) -> bool:
for line in data:
if sum(line) > 0:
return False
return True
def increase_adjacent(self, data, x, y):
d = {
'right': [x, y + 1],
'left': [x, y - 1],
'down': [x + 1, y],
'down_right': [x + 1, y + 1],
'down_left': [x + 1, y - 1],
'top': [x - 1, y],
'top_right': [x - 1, y + 1],
'top_left': [x - 1, y - 1]
}
for pos in d.values():
x, y = pos
if self.is_within_row(x) and self.is_within_column(y):
if data[x][y] != 0:
data[x][y] += 1
if data[x][y] > 9:
data[x][y] = 0
self.flashes += 1
self.increase_adjacent(data, x, y)
def is_within_column(self, number) -> bool:
return 0 <= number <= self.column_length
def is_within_row(self, number) -> bool:
return 0 <= number <= self.row_length
@staticmethod
def get_puzzle_input() -> list:
lst = []
with open("input.txt") as file:
for line in file:
lst.append(list(line.rstrip()))
return lst
day = Day11()
print(f'Result part 1: {day.part_one()}')
print(f'Result part 2: {day.part_two()}')