@@ 5,11 5,14 @@ cat input.txt | python puzzle_1.py
"""
import sys
+
def print_octopi(octopi):
for row in octopi:
for col in row:
sys.stdout.write(f"{col} ")
sys.stdout.write("\n")
+ sys.stdout.write("\n")
+
if __name__ == "__main__":
octopi = list(
@@ 18,17 21,83 @@ if __name__ == "__main__":
sys.stdin.read().splitlines(),
)
)
- print_octopi(octopi)
- for step in range(1, 2 + 1):
- print("step", step)
+ WIDTH = len(octopi[0])
+ HEIGHT = len(octopi)
+ flash_count = 0
+ for step in range(1, 100 + 1):
# Increment energy levels
octopi = list(
map(lambda row: list(map(lambda energy: energy + 1, row)), octopi)
)
# Look for flashes
- for row_index, row in enumerate(octopi):
- for col_index, energy in enumerate(row):
- if energy > 9:
- octopi[row_index][col_index] = 0
+ found_flashes = True
+ while found_flashes:
+ found_flashes = False
+ for row_index in range(HEIGHT):
+ for col_index in range(WIDTH):
+ energy = octopi[row_index][col_index]
+ if energy > 9:
+ flash_count += 1
+ found_flashes = True
+ # Found flash
+ # Set to -1 to not flash twice in a step
+ # https://barretblake.dev/blog/2021/12/advent-of-code-day11/
+ octopi[row_index][col_index] = -1
+
+ # Increment surrounding octopi
+ # NW
+ if (
+ row_index > 0
+ and col_index > 0
+ and octopi[row_index - 1][col_index - 1] > -1
+ ):
+ octopi[row_index - 1][col_index - 1] += 1
+ # N
+ if row_index > 0 and octopi[row_index - 1][col_index] > -1:
+ octopi[row_index - 1][col_index] += 1
+ # NE
+ if (
+ row_index > 0
+ and col_index < (WIDTH - 1)
+ and octopi[row_index - 1][col_index + 1] > -1
+ ):
+ octopi[row_index - 1][col_index + 1] += 1
+ # E
+ if (
+ col_index < (WIDTH - 1)
+ and octopi[row_index][col_index + 1] > -1
+ ):
+ octopi[row_index][col_index + 1] += 1
+ # SE
+ if (
+ row_index < (HEIGHT - 1)
+ and col_index < (WIDTH - 1)
+ and octopi[row_index + 1][col_index + 1] > -1
+ ):
+ octopi[row_index + 1][col_index + 1] += 1
+ # S
+ if (
+ row_index < (HEIGHT - 1)
+ and octopi[row_index + 1][col_index] > -1
+ ):
+ octopi[row_index + 1][col_index] += 1
+ # SW
+ if (
+ row_index < (HEIGHT - 1)
+ and col_index > 0
+ and octopi[row_index + 1][col_index - 1] > -1
+ ):
+ octopi[row_index + 1][col_index - 1] += 1
+ # W
+ if col_index > 0 and octopi[row_index][col_index - 1] > -1:
+ octopi[row_index][col_index - 1] += 1
+
+ # Set -1's to 0's
+ octopi = list(
+ map(
+ lambda row: list(map(lambda energy: energy if energy >= 0 else 0, row)),
+ octopi,
+ )
+ )
- print_octopi(octopi)
+ sys.stdout.write(str(flash_count))