Created
December 11, 2021 16:52
-
-
Save albertein/95c2318f859e18afab5e8b76140c6b71 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def key(x,y): | |
return "{0}-{1}".format(x, y) | |
def energize(octopi, x, y, flashed): | |
if y < 0 or y >= len(octopi) or x < 0 or x >= len(octopi[y]): | |
return | |
if key(x, y) in flashed: | |
return | |
octopi[y][x] += 1 | |
if octopi[y][x] > 9: | |
flashed[key(x, y)] = (x, y) | |
energize(octopi, x - 1, y - 1, flashed) | |
energize(octopi, x, y - 1, flashed) | |
energize(octopi, x + 1, y - 1, flashed) | |
energize(octopi, x - 1, y, flashed) | |
energize(octopi, x + 1, y, flashed) | |
energize(octopi, x - 1, y + 1, flashed) | |
energize(octopi, x, y + 1, flashed) | |
energize(octopi, x + 1, y + 1, flashed) | |
def simulate(octopi): | |
flashed = {} | |
for y, row in enumerate(octopi): | |
for x, _ in enumerate(row): | |
energize(octopi, x, y, flashed) | |
for key in flashed: | |
x, y = flashed[key] | |
octopi[y][x] = 0 | |
return len(flashed) | |
if __name__ == '__main__': | |
with open('input.txt') as data: | |
octopi = [] | |
for line in data: | |
line = line.strip() | |
octopi.append([int(item) for item in line]) | |
flashes = 0 | |
flashes_at_100 = 0 | |
step = 0 | |
while True: | |
step += 1 | |
step_flashes = simulate(octopi) | |
flashes += step_flashes | |
if step == 100: | |
flashes_at_100 = flashes | |
if step_flashes == len(octopi) * len(octopi[0]): | |
break | |
print(flashes_at_100, step) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment