summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorBrian Chu <brianmchu42@gmail.com>2021-12-09 00:28:53 -0800
committerBrian Chu <brianmchu42@gmail.com>2021-12-09 00:28:53 -0800
commitb9b5574179dcbb5f6d3fa0715905a047d1cd377e (patch)
tree110611b76b770e25c420f11ee6c8986c49584d67
parent074c48b33e3b4fa31e0cdfba357e727fe18f2a5f (diff)
downloadAdventOfCode2021-b9b5574179dcbb5f6d3fa0715905a047d1cd377e.tar.gz
solution for day 9
-rw-r--r--day9.py33
1 files changed, 33 insertions, 0 deletions
diff --git a/day9.py b/day9.py
new file mode 100644
index 0000000..d0f8b1f
--- /dev/null
+++ b/day9.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+import numpy as np
+from scipy.ndimage import label
+
+with open("day9.txt") as data:
+    depthmap = []
+    for line in data:
+        row = [int(num) for num in line.strip()]
+        depthmap.append(row)
+    depthmap = np.array(depthmap)
+
+# part 1
+# convolve across grid
+
+def conv_filter(position: (int, int)) -> int:
+    def neighbors():
+        x, y = position
+        neighboring = {(x-1, y), (x+1, y), (x, y-1), (x, y+1)}
+        return {(xPos, yPos) for xPos, yPos in neighboring if 0 <= xPos <= depthmap.shape[0]-1 and 0 <= yPos <= depthmap.shape[1]-1}
+
+    if all(depthmap[position] < depthmap[pos] for pos in neighbors()):
+        return depthmap[position] + 1
+    else:
+        return 0
+
+print(sum(conv_filter((x, y)) for x in range(depthmap.shape[0]) for y in range(depthmap.shape[1])))
+
+# part 2
+basins, num_basins = label(depthmap != 9)
+counts = [np.count_nonzero(basins == num) for num in range(1, num_basins + 1)]
+counts.sort()
+print(np.prod(counts[-3:]))