Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (def cave (->> "/home/bobini/Pulpit/cave.txt"
- slurp
- clojure.string/trim
- clojure.string/split-lines
- (map clojure.string/trim)
- (map (fn [line] (map #(Character/digit % 10) line)))
- (map vec)
- vec))
- (defn adjacent-coords [y x y-max x-max]
- (cond-> []
- (> x 0) (conj [y (dec x)])
- (> y 0) (conj [(dec y) x])
- (< y y-max) (conj [(inc y) x])
- (< x x-max) (conj [y (inc x)])))
- (defn any-adjacent-lower? [cave y x y-max x-max]
- (some #(<= % (get-in cave [y x]))
- (map #(get-in cave %)
- (adjacent-coords y x y-max x-max))))
- (defn get-low-points [cave]
- (let [y-max (dec (count cave))
- x-max (dec (count (first cave)))]
- (reduce #(if (not (any-adjacent-lower? cave (first %2) (second %2) y-max x-max))
- (conj %1 %2)
- %1)
- []
- (for [y (range (inc y-max))
- x (range (inc x-max))]
- [y x]))))
- (defn find-first-unfilled [cave coords]
- (first (filter #(not= 9 (get-in cave %)) coords)))
- (defn fill-one-basin [cave start]
- (let [y-max (dec (count cave))
- x-max (dec (count (first cave)))]
- (loop [cave cave
- size 0
- queue #{start}]
- (if (empty? queue)
- [cave size]
- (let [current (first queue)]
- (if (= 9 (get-in cave current))
- (recur cave size (disj queue current))
- (recur (assoc-in cave current 9)
- (inc size)
- (-> queue
- (disj current)
- (into (adjacent-coords
- (first current) (second current)
- y-max x-max))))))))))
- (defn count-basin-sizes [cave]
- (let [y-max (dec (count cave))
- x-max (dec (count (first cave)))
- coords (for [y (range (inc y-max))
- x (range (inc x-max))]
- [y x])]
- (loop [cave cave
- sizes []]
- (if-let [start (find-first-unfilled cave coords)]
- (let [[new-cave size] (fill-one-basin cave start)]
- (recur new-cave (conj sizes size)))
- sizes))))
- (def answer9-2 (apply * (->> cave
- count-basin-sizes
- sort
- reverse
- (take 3))))
Advertisement
Add Comment
Please, Sign In to add comment