You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
1.6 KiB
Python
81 lines
1.6 KiB
Python
from time import sleep
|
|
|
|
with open("input") as f:
|
|
lights = [n.strip() for n in f.readlines()]
|
|
|
|
STEPS = 100
|
|
# STEPS = 4
|
|
|
|
X_MAX = len(lights)
|
|
Y_MAX = len(lights[0])
|
|
|
|
|
|
def print_lights():
|
|
for row in lights:
|
|
print(row)
|
|
|
|
|
|
def neighbors_that_are_on(center_x, center_y):
|
|
count = 0
|
|
for d_x in range(-1, 2):
|
|
for d_y in range(-1, 2):
|
|
x = center_x + d_x
|
|
y = center_y + d_y
|
|
if d_x == 0 and d_y == 0:
|
|
continue
|
|
if x < 0 or x >= X_MAX:
|
|
continue
|
|
if y < 0 or y >= Y_MAX:
|
|
continue
|
|
neighbor = lights[x][y]
|
|
if neighbor == "#":
|
|
count += 1
|
|
return count
|
|
|
|
|
|
def get_next_state(prev_state, neighbors_count):
|
|
if prev_state == "#":
|
|
if neighbors_count in [2, 3]:
|
|
return "#"
|
|
else:
|
|
return "."
|
|
else: # light == '.'
|
|
if neighbors_count == 3:
|
|
return "#"
|
|
else:
|
|
return "."
|
|
|
|
|
|
print("Initial state")
|
|
print_lights()
|
|
print()
|
|
|
|
for step in range(STEPS):
|
|
new_lights = []
|
|
|
|
for x in range(X_MAX):
|
|
line = ""
|
|
for y in range(Y_MAX):
|
|
light = lights[x][y]
|
|
neighbors_count = neighbors_that_are_on(x, y)
|
|
next_state = get_next_state(light, neighbors_count)
|
|
line += next_state
|
|
new_lights.append(line)
|
|
|
|
lights = new_lights
|
|
print("Step", step + 1)
|
|
print_lights()
|
|
print()
|
|
sleep(0.03)
|
|
|
|
|
|
count = 0
|
|
for line in lights:
|
|
for light in line:
|
|
if light == "#":
|
|
count += 1
|
|
|
|
print(count)
|
|
|
|
# 353: too low
|