Skip to content

Instantly share code, notes, and snippets.

@quephird
Created December 9, 2022 02:06
Show Gist options
  • Save quephird/011cd06d009b8ac93414e1235d0503b1 to your computer and use it in GitHub Desktop.
Save quephird/011cd06d009b8ac93414e1235d0503b1 to your computer and use it in GitHub Desktop.
(require ['clojure.string :as 'str])
(defn to-vec-of-ints [line]
(->> line
(map #(Integer/parseInt (str %)))
vec))
(defn to-grid [trees]
(->> trees
(map to-vec-of-ints)
vec))
(defn parse-input [filename]
(->> filename
slurp
str/split-lines
to-grid))
(defn trees-to-left-edge [[x y] grid]
(as-> grid $
(nth $ y)
(take x $)
(reverse $)))
(defn trees-to-right-edge [[x y] grid]
(as-> grid $
(nth $ y)
(drop (inc x) $)))
(defn trees-to-top-edge [[x y] grid]
(->> grid
(map #(nth % x))
(take y)
reverse))
(defn trees-to-bottom-edge [[x y] grid]
(->> grid
(map #(nth % x))
(drop (inc y))))
(defn visible? [[x y] grid]
(let [width (count (first grid))
height (count grid)]
(if (or (zero? x)
(zero? y)
(= (dec width) x)
(= (dec height) y))
true
(let [tree (get-in grid [y x])]
(or (every? #(< % tree) (trees-to-left-edge [x y] grid))
(every? #(< % tree) (trees-to-right-edge [x y] grid))
(every? #(< % tree) (trees-to-top-edge [x y] grid))
(every? #(< % tree) (trees-to-bottom-edge [x y] grid)))))))
(defn count-visible [grid]
(->> (for [x (range 0 (count (first grid)))
y (range 0 (count grid))]
(visible? [x y] grid))
(filter true?)
count))
(defn solution-part-1 [filename]
(-> filename
parse-input
count-visible))
(defn partial-score [tree other-trees]
(loop [score 0
[next-tree & rest-of-trees] other-trees]
(cond
(nil? next-tree)
score
(<= tree next-tree)
(inc score)
:else
(recur (inc score) rest-of-trees))))
(defn scenic-score [[x y] grid]
(let [tree (get-in grid [y x])]
(* (partial-score tree (trees-to-left-edge [x y] grid))
(partial-score tree (trees-to-right-edge [x y] grid))
(partial-score tree (trees-to-top-edge [x y] grid))
(partial-score tree (trees-to-bottom-edge [x y] grid)))))
(defn max-scenic-score [grid]
(->> (for [x (range 0 (count (first grid)))
y (range 0 (count grid))]
(scenic-score [x y] grid))
(apply max)))
(defn solution-part-2 [filename]
(-> filename
parse-input
max-scenic-score))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment