""" Simulate octopus flashing """ import time import random rows = 3 cols = 3 def increment(octopodes, position): for x in range(position[0] - 1, position[0] + 2): if x < 0 or x > cols - 1: continue for y in range(position[1] - 1, position[1] + 2): if y < 0 or y > rows - 1: continue octopodes[y][x] += 1 def add_one(octopodes): for y in range(rows): for x in range(cols): octopodes[y][x] += 1 def flash(octopodes): flashed = [] flashed_this_iter = True while flashed_this_iter: flashed_this_iter = False for y in range(rows): for x in range(cols): if octopodes[y][x] > 9 and (x, y) not in flashed: flashed_this_iter = True flashed.append((x, y)) increment(octopodes, (x, y)) for x, y in flashed: octopodes[y][x] = 0 #for y in range(20): # display_row = [] # for x in range(40): # if (x, y) in flashed: # display_row.append("X") # else: # display_row.append(".") # print("".join(display_row)) return len(flashed) octopodes = [] for i in range(rows): octopodes.append([random.randint(0, 9) for _ in range(cols)]) for gen in range(1, 100000000): add_one(octopodes) n_flashed = flash(octopodes) if gen % 100 == 0: print("###", gen, "###", n_flashed) if n_flashed == (rows * cols): break print(gen)