Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (defmulti get-in (fn [g & _] (:type g)))
- (defmethod get-in :grid [grid [y x :as path]]
- (cond
- (> y (count (:val grid))) true
- (or (= y (count (:val grid))) (>= x (-> grid :val first count)))
- (clojure.core/get-in (:floor grid) path false)
- :else (clojure.core/get-in (:val grid) path)))
- (defmethod get-in :default [g p] (clojure.core/get-in g p))
- (defmulti assoc-in (fn [g & _] (:type g)))
- (defmethod assoc-in :grid [grid [y x :as path] value]
- (if
- (or (= y (count (:val grid))) (>= x (-> grid :val first count)))
- (clojure.core/assoc-in grid (into [:floor] path) value)
- (clojure.core/assoc-in grid (into [:val] path) value)))
- (defmethod assoc-in :default [g p v] (clojure.core/assoc-in g p v))
- (defn update-grid [grid [y x :as start]]
- (cond
- (nil? (get-in grid start)) nil
- (not (true? (get-in grid [(inc y) x]))) (recur grid [(inc y) x])
- (not (true? (get-in grid [(inc y) (dec x)]))) (recur grid [(inc y) (dec x)])
- (not (true? (get-in grid [(inc y) (inc x)]))) (recur grid [(inc y) (inc x)])
- (true? (get-in grid start)) nil
- :else (assoc-in grid start true)
- ))
- (defn tick [grid]
- (loop [ticks 0 g grid]
- (if
- (nil? g) ticks
- (recur (inc ticks) (update-grid g [0 500])))))
- (defn add-rocks [grid steps]
- (first (reduce
- (fn [[grid [a b]] [c d]]
- [(reduce
- #(assoc-in %1 %2 true)
- grid
- (cond
- (< a c) (map (fn [x] [b x]) (range a (inc c)))
- (> a c) (map (fn [x] [b x]) (range c (inc a)))
- (< b d) (map (fn [y] [y a]) (range b (inc d)))
- (> b d) (map (fn [y] [y a]) (range d (inc b)))))
- [c d]])
- [grid (first steps)]
- (rest steps))))
- (with-open [rdr (clojure.java.io/reader "sand.in")]
- (let
- [steps
- (->> rdr
- line-seq
- (map #(clojure.string/split % #" -> "))
- (map flatten)
- (map (fn [steps] (map #(clojure.string/split % #",") steps)))
- (map flatten)
- (map (fn [steps] (map #(Integer/parseInt %) steps)))
- (map (partial partition 2)))
- [maxx maxy] (->> steps flatten (partition 2) (apply map vector) (map #(apply max %)))
- grid (vec (repeat (inc maxy) (vec (repeat (inc maxx) false))))
- ]
- (->> steps (reduce add-rocks grid) tick dec println)
- (->> steps (reduce add-rocks {:type :grid, :val grid, :floor {}}) tick dec println)
- ))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement