input_file = "input.txt" # -1 is floor # 0 is empty seat # 1 is occupied seat # Map represents each cell with [current_state,next_state] # Would a dictionary be better ? seating_map = [] def load_map(): with open(input_file) as text_map: line = text_map.readline().strip("\n") while line: seating_map.append([]) for character in line: # Set every seat to occupied as its the first iteration anyway seating_map[-1].append([1 if character == 'L' else -1, 1]) line = text_map.readline().strip("\n") def run_adjacent_seats(): """ Run the cellular automata with the following rules : If empty and adjacent are empty, seat If seated and 4 or more neighbours, become empty If floor, pass """ load_map() game_stable = False occupied_seats = 0 iteration = 0 while not game_stable: for i in range(len(seating_map)): for j in range(len(seating_map[0])): current_cell = seating_map[i][j] if current_cell[0] < 0: continue seated_neighbours = 0 for cell_position in [(i+di, j+dj) for di in [-1, 0, 1] for dj in [-1, 0, 1]]: if cell_position != (i, j) and \ 0 <= cell_position[0] < len(seating_map) and 0 <= cell_position[1] < len(seating_map[0]): seated_neighbours += 1 if seating_map[cell_position[0]][cell_position[1]][0] > 0 else 0 if current_cell[0] == 0 and seated_neighbours == 0: current_cell[1] = 1 elif current_cell[0] == 1 and seated_neighbours >= 4: current_cell[1] = 0 game_stable = True occupied_seats = 0 # Should be integrated to the first loop to speed things up for i in range(len(seating_map)): for j in range(len(seating_map[0])): current_cell = seating_map[i][j] if current_cell[0] < 0: continue if game_stable and current_cell[0] != current_cell[1]: game_stable = False current_cell[0] = current_cell[1] occupied_seats += current_cell[0] iteration += 1 print(f"The number of occupied seats when stabilized is {occupied_seats}") run_adjacent_seats()