advent_of_code/11/11_2.py

108 lines
2.8 KiB
Python
Raw Normal View History

2021-12-11 19:30:03 +01:00
#!/usr/bin/env python
# 2021 - Advent Of Code - 11 part 2
GRID_SIZE = 10
def parse_file(file):
2022-04-05 13:27:24 +02:00
with open(file, encoding="utf-8") as f:
2021-12-11 19:30:03 +01:00
columns = []
for line in f.readlines():
columns.append([int(c) for c in line.strip()])
return columns
def print_grid(grid):
for y in range(GRID_SIZE):
for x in range(GRID_SIZE):
print(grid[y][x], end='')
print()
print()
def check_flash(grid, f):
for y in range(GRID_SIZE):
for x in range(GRID_SIZE):
if grid[y][x] > 9:
f = flash(grid, x, y, f)
return f
def flash(grid, x, y, f):
2022-04-05 14:02:10 +02:00
# pylint: disable=R0912
2021-12-11 19:30:03 +01:00
grid[y][x] = 0
f += 1
if y > 0: # upper neighbours
if x > 0:
if grid[y-1][x-1] != 0: # 1
grid[y-1][x-1] += 1
if grid[y-1][x-1] > 9:
f = flash(grid, x-1, y-1, f)
if grid[y-1][x] != 0: # 2
grid[y-1][x] += 1
if grid[y-1][x] > 9:
f = flash(grid, x, y-1, f)
if x < GRID_SIZE-1:
if grid[y-1][x+1] != 0: # 3
grid[y-1][x+1] += 1
if grid[y-1][x+1] > 9:
f = flash(grid, x+1, y-1, f)
if x > 0: # middle neighbours
if grid[y][x-1] != 0: # 4
grid[y][x-1] += 1
if grid[y][x-1] > 9:
f = flash(grid, x-1, y, f)
if x < GRID_SIZE - 1: # 6
if grid[y][x+1] != 0:
grid[y][x+1] += 1
if grid[y][x+1] > 9:
f = flash(grid, x+1, y, f)
if y < GRID_SIZE-1: # down neighbours
if x > 0:
if grid[y+1][x-1] != 0: # 7
grid[y+1][x-1] += 1
if grid[y+1][x-1] > 9:
f = flash(grid, x-1, y+1, f)
if grid[y+1][x] != 0: # 8
grid[y+1][x] += 1
if grid[y + 1][x] > 9:
f = flash(grid, x, y+1, f)
if x < GRID_SIZE-1:
if grid[y+1][x+1] != 0: # 9
grid[y+1][x+1] += 1
if grid[y+1][x+1] > 9:
f = flash(grid, x+1, y+1, f)
return f
octopus_map = parse_file('input.txt')
# octopus_map = parse_file('input_example.txt')
print_grid(octopus_map)
nbflash = 0
# for step in range(1000):
full_flash = False
step = 0
while not full_flash:
full_flash = True
# increase all energy levels
for mapy in range(GRID_SIZE):
for mapx in range(GRID_SIZE):
if octopus_map[mapy][mapx] != 0:
full_flash = False
octopus_map[mapy][mapx] += 1
nbflash = check_flash(octopus_map, nbflash)
# check full flash
if full_flash:
print(f'Full flash at {step}')
step += 1
print_grid(octopus_map)
print(f'number of flash: {nbflash}')