day9: improved both parts

master
Clyne 3 years ago
parent 894df68d23
commit e6afd7fe60

@ -5,33 +5,17 @@
(mapv (partial mapv #(- (int %) 48)))
))
(defn compare-heights [a b]
(if (or (nil? a) (nil? b) (< a b)) 1 0))
(defn get-adj [y x]
(map (partial get-in input-map)
[[(dec y) x] [(inc y) x] [y (dec x)] [y (inc x)]]))
(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
)
)
)
)
)
(->> (for [y (range 0 (count input-map))
x (range 0 (count (first input-map)))
:let [height (get-in input-map [y x])]
:when (every? #(or (nil? %) (< height %))
(get-adj y x))]
(inc height))
(apply +)
(println)
)

@ -1,9 +1,4 @@
(def input-map
(->> (slurp "./in")
(clojure.string/split-lines)
(mapv vec)
(mapv (partial mapv #(- (int %) 48)))
))
(require '[clojure.set])
(defn get-adj
"Gets vector of coords surrounding (x, y)."
@ -11,18 +6,16 @@
(defn basin-continues?
"Determines if `b` is a continuation of the basin that includes `a`."
[a b]
(and (some? b) (not= b 9) (> b a)))
[a b] (and (some? b) (not= b 9) (> b a)))
(defn basin-bottom?
"Determines if point `p` in `hmap` is the bottom of a basin surrounded by
points `adj`."
[hmap p adj]
(empty?
(filter
#(let [q (get-in hmap %)] (and (some? q) (> (get-in hmap p) q)))
adj
)))
(every?
#(let [q (get-in hmap %)] (or (nil? q) (< (get-in hmap p) q)))
adj
))
(defn find-basin
"If point `yx` in `hmap` is in a basin (determined using `adj`), return a
@ -31,21 +24,19 @@
(let [res (filter #(basin-continues? (get-in hmap yx)
(get-in hmap %))
adj)]
(if-not (empty? res)
(apply
(partial concat res)
(map
#(find-basin hmap % (apply get-adj %))
res
)))))
(->> (for [y (range 0 (count input-map))
x (range 0 (count (first input-map)))]
(let [adj (get-adj y x)]
(when (basin-bottom? input-map [y x] adj)
(inc (count (distinct (find-basin input-map [y x] adj))))
(apply (partial clojure.set/union res)
(map #(set (find-basin hmap % (apply get-adj %))) res)
)))
(filter some?)
(->> (slurp "./in")
(clojure.string/split-lines)
(mapv vec)
(mapv (partial mapv #(- (int %) 48)))
(#(for [y (range 0 (count %))
x (range 0 (count (first %)))
:let [adj (get-adj y x)]
:when (basin-bottom? % [y x] adj)]
(inc (count (find-basin % [y x] adj)))))
(sort >)
(take 3)
(apply *)

Loading…
Cancel
Save