From 7a62286670ae00a77264054c71723af0f65e234c Mon Sep 17 00:00:00 2001 From: Clyne Sullivan Date: Thu, 9 Dec 2021 09:01:17 -0500 Subject: [PATCH] add day 9 --- day9/part1.clj | 37 +++++++++++++++++++++++++++++ day9/part2.clj | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 day9/part1.clj create mode 100644 day9/part2.clj 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 + )))))))) +