aboutsummaryrefslogtreecommitdiffstats
path: root/day9
diff options
context:
space:
mode:
authorClyne Sullivan <clyne@bitgloo.com>2021-12-09 09:01:17 -0500
committerClyne Sullivan <clyne@bitgloo.com>2021-12-09 09:01:17 -0500
commit7a62286670ae00a77264054c71723af0f65e234c (patch)
tree3305c2c4a957b285a8dd30101976b2f818868850 /day9
parent17362b34ccec35de208713610e9dd3d6d1eec024 (diff)
add day 9
Diffstat (limited to 'day9')
-rw-r--r--day9/part1.clj37
-rw-r--r--day9/part2.clj64
2 files changed, 101 insertions, 0 deletions
diff --git a/day9/part1.clj b/day9/part1.clj
new file mode 100644
index 0000000..813d5a6
--- /dev/null
+++ b/day9/part1.clj
@@ -0,0 +1,37 @@
+(def input-map
+ (->> (slurp "./in")
+ (clojure.string/split-lines)
+ (mapv vec)
+ (mapv (partial mapv #(- (int %) 48)))
+ ))
+
+(defn compare-heights [a b]
+ (if (or (nil? a) (nil? b) (< a b)) 1 0))
+
+(println
+ (apply +
+ (for [y (range 0 (count input-map))
+ x (range 0 (count (first input-map)))]
+ (let [height (get-in input-map [y x])]
+ (if
+ (= 4
+ (apply +
+ (map
+ (partial compare-heights height)
+ [
+ (get-in input-map [(dec y) x])
+ (get-in input-map [(inc y) x])
+ (get-in input-map [y (dec x)])
+ (get-in input-map [y (inc x)])
+ ]
+ )
+ )
+ )
+ (inc height)
+ 0
+ )
+ )
+ )
+ )
+ )
+
diff --git a/day9/part2.clj b/day9/part2.clj
new file mode 100644
index 0000000..455cb39
--- /dev/null
+++ b/day9/part2.clj
@@ -0,0 +1,64 @@
+(def input-map
+ (->> (slurp "./in")
+ (clojure.string/split-lines)
+ (mapv vec)
+ (mapv (partial mapv #(- (int %) 48)))
+ ))
+
+(defn basin-bottom-single? [a b]
+ (if (or (nil? a) (nil? b) (< a b)) 1 0))
+
+(defn basin-continues? [a b]
+ (and (some? b) (not= b 9) (> b a)))
+
+(defn basin-bottom? [hmap p adj]
+ (= 4
+ (apply +
+ (map
+ #(basin-bottom-single?
+ (get-in hmap p)
+ (get-in hmap %))
+ adj
+ ))))
+
+(defn get-adj [y x]
+ [[(dec y) x]
+ [(inc y) x]
+ [y (dec x)]
+ [y (inc x)]])
+
+(defn find-basin [hmap y x adj]
+ (let [res (reduce
+ #(if
+ (basin-continues? (get-in hmap [y x])
+ (get-in hmap %2))
+ (conj %1 %2)
+ %1)
+ []
+ adj
+ )]
+ (if (empty? res)
+ []
+ (apply
+ (partial concat res)
+ (map
+ #(find-basin hmap (first %) (second %) (apply get-adj %))
+ res))
+ )
+ )
+ )
+
+(println
+ (apply *
+ (take 3
+ (sort >
+ (filter
+ pos?
+ (for [y (range 0 (count input-map))
+ x (range 0 (count (first input-map)))]
+ (let [adj (get-adj y x)]
+ (if (basin-bottom? input-map [y x] adj)
+ (count (distinct (concat [[y x]] (find-basin input-map y x adj))))
+ 0
+ ))))))))
+