-
Notifications
You must be signed in to change notification settings - Fork 1
/
day11.py
144 lines (96 loc) · 3.1 KB
/
day11.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
from copy import deepcopy
with open("inputs/day11.txt") as file:
data = [line.strip() for line in file]
def update1():
global grid
for row in range(rows):
for col in range(cols):
seat = grid[row][col]
adjacent = ((-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0))
if seat == "L":
free = True
for coords in adjacent:
row_ = coords[0]
col_ = coords[1]
if len(grid) > row + row_ >= 0 and len(grid[0]) > col + col_ >= 0:
if grid[row + row_][col + col_] == "#":
free = False
break
if free:
new_grid[row][col] = "#"
elif seat == "#":
count = 0
for coords in adjacent:
row_ = coords[0]
col_ = coords[1]
if rows > row + row_ >= 0 and cols > col + col_ >= 0:
if grid[row + row_][col + col_] == "#":
count += 1
if count >= 4:
new_grid[row][col] = "L"
grid = deepcopy(new_grid)
def update2():
global grid
for row in range(rows):
for col in range(cols):
seat = grid[row][col]
adjacent = ((-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0))
if seat == "L":
free = True
for coords in adjacent:
if sees_occupied(row, col, *coords):
free = False
break
if free:
new_grid[row][col] = "#"
elif seat == "#":
count = 0
for coords in adjacent:
if sees_occupied(row, col, *coords):
count += 1
if count >= 5:
new_grid[row][col] = "L"
grid = deepcopy(new_grid)
def occupied_seats():
total = 0
for row in grid:
total += row.count("#")
return total
def sees_occupied(row, col, delta_row, delta_col):
while rows > row + delta_row >= 0 and cols > col + delta_col >= 0:
col += delta_col
row += delta_row
if grid[row][col] == "#":
return True
elif grid[row][col] == "L":
return False
return False
# Part 1 ===
grid = [list(line) for line in data]
new_grid = deepcopy(grid)
rows = len(grid)
cols = len(grid[0])
occupied = -1
occupied_last = -1
while True:
update1()
occupied = occupied_seats()
if occupied == occupied_last:
part1 = occupied
break
occupied_last = occupied
# Part 2 ===
grid = [list(line) for line in data]
new_grid = deepcopy(grid)
occupied = -1
occupied_last = -1
while True:
update2()
occupied = occupied_seats()
if occupied == occupied_last:
part2 = occupied
break
occupied_last = occupied
print("Part 1:", part1)
print("Part 2:", part2)
print(part1 == 2178 and part2 == 1978)