aboutsummaryrefslogtreecommitdiff
path: root/2021/day11
diff options
context:
space:
mode:
Diffstat (limited to '2021/day11')
-rw-r--r--2021/day11/11a.py42
-rw-r--r--2021/day11/11b.py44
2 files changed, 86 insertions, 0 deletions
diff --git a/2021/day11/11a.py b/2021/day11/11a.py
new file mode 100644
index 0000000..1c6d096
--- /dev/null
+++ b/2021/day11/11a.py
@@ -0,0 +1,42 @@
+def adjacent(coord, arr):
+ x, y = coord
+ max_x = len(arr[y]) - 1
+ max_y = len(arr) - 1
+ for dx in [-1, 0, 1]:
+ for dy in [-1, 0, 1]:
+ xp, yp = (x + dx, y + dy)
+ if ((xp, yp) == coord or min(xp, yp) < 0 or xp > max_x or yp > max_y):
+ continue
+ yield (xp, yp)
+
+def flash(coord, arr, flashed):
+ flashed.add(coord)
+ for (x, y) in adjacent(coord, arr):
+ arr[y][x] += 1
+ visit((x, y), arr, flashed)
+
+def visit(coord, arr, flashed):
+ x, y = coord
+ v = arr[y][x]
+ if v > 9 and coord not in flashed:
+ flash(coord, arr, flashed)
+
+def step(arr):
+ flashed = set()
+ for (x,y) in ((x,y) for (y,l) in enumerate(arr) for (x,_) in enumerate(l)):
+ arr[y][x] = arr[y][x] + 1
+ visit((x,y), arr, flashed)
+ for (x,y) in flashed:
+ arr[y][x] = 0
+ return len(flashed)
+
+def print_board(arr):
+ print("\n".join(["".join(map(str, l)) for l in arr]))
+
+state = [[int(n) for n in l] for l in open("./input").read().strip().split("\n")]
+total_flashes = 0
+for _ in range(0, 100):
+ flashes = step(state)
+ total_flashes += flashes
+
+print(total_flashes)
diff --git a/2021/day11/11b.py b/2021/day11/11b.py
new file mode 100644
index 0000000..18b45d4
--- /dev/null
+++ b/2021/day11/11b.py
@@ -0,0 +1,44 @@
+def adjacent(coord, arr):
+ x, y = coord
+ max_x = len(arr[y]) - 1
+ max_y = len(arr) - 1
+ for dx in [-1, 0, 1]:
+ for dy in [-1, 0, 1]:
+ xp, yp = (x + dx, y + dy)
+ if ((xp, yp) == coord or min(xp, yp) < 0 or xp > max_x or yp > max_y):
+ continue
+ yield (xp, yp)
+
+def flash(coord, arr, flashed):
+ flashed.add(coord)
+ for (x, y) in adjacent(coord, arr):
+ arr[y][x] += 1
+ visit((x, y), arr, flashed)
+
+def visit(coord, arr, flashed):
+ x, y = coord
+ v = arr[y][x]
+ if v > 9 and coord not in flashed:
+ flash(coord, arr, flashed)
+
+def step(arr):
+ flashed = set()
+ for (x,y) in ((x,y) for (y,l) in enumerate(arr) for (x,_) in enumerate(l)):
+ arr[y][x] = arr[y][x] + 1
+ visit((x,y), arr, flashed)
+ for (x,y) in flashed:
+ arr[y][x] = 0
+ return len(flashed)
+
+def print_board(arr):
+ print("\n".join(["".join(map(str, l)) for l in arr]))
+
+state = [[int(n) for n in l] for l in open("./input").read().strip().split("\n")]
+total_squares = sum([len(l) for l in state])
+n = 0
+while True:
+ n += 1
+ if step(state) == total_squares:
+ break
+
+print(n)