fix memoization

This commit is contained in:
Adam Jeniski 2023-12-14 20:29:55 -05:00
parent da6af5f342
commit 65a4aaeca3

View File

@ -7,53 +7,57 @@
(update 1 #(->> (str/split % #",") (update 1 #(->> (str/split % #",")
(mapv parse-long))))) (mapv parse-long)))))
(defn make-anso [] (defn ans [dots blocks]
(with-local-vars (let [dp (atom {})
[ans (memoize f
(fn f [dots blocks i bi current] (fn f [dots blocks i bi current]
(let [len-blocks (count blocks) (or (@dp [i bi current])
dot_i (when (< i (count dots)) (get dots i))] (let [len-blocks (count blocks)
(if (= i (count dots)) dot_i (when (< i (count dots)) (get dots i))
(cond (and (= bi len-blocks) v (if (= i (count dots))
(= current 0)) (cond (and (= bi len-blocks)
1 (= current 0))
(and (= bi (dec len-blocks)) 1
(= current (get blocks bi))) (and (= bi (dec len-blocks))
1 (= current (get blocks bi)))
:else 1
0) :else
(->> [\. \#] 0)
(map #(if (or (= dot_i %) (->> [\. \#]
(= dot_i \?)) (map #(if (or (= dot_i %)
(cond (and (= % \.) (= dot_i \?))
(= current 0)) (cond (and (= % \.)
(f dots blocks (inc i) bi 0) (= current 0))
(f dots blocks (inc i) bi 0)
(and (= % \.) (and (= % \.)
(> current 0) (> current 0)
(< bi len-blocks) (< bi len-blocks)
(= (get blocks bi) current)) (= (get blocks bi) current))
(f dots blocks (inc i) (inc bi) 0) (f dots blocks (inc i) (inc bi) 0)
(= % \#) (= % \#)
(f dots blocks (inc i) bi (inc current)) (f dots blocks (inc i) bi (inc current))
:else 0) :else 0)
0)) 0))
(reduce +))))))] (reduce +)))]
(.bindRoot ans @ans) (swap! dp assoc [i bi current] v)
@ans)) v)))]
(f dots blocks 0 0 0)))
;; part 1
(->> (get-puzzle-input 12) (->> (get-puzzle-input 12)
(map parse-line) (map parse-line)
(map #((make-anso) (first %) (second %) 0 0 0)) (map #(ans (first %) (second %)))
(reduce +)) (reduce +))
;; part 2
(->> (get-puzzle-input 12) (->> (get-puzzle-input 12)
(map parse-line) (map parse-line)
(mapv (fn [[s cnts]] (mapv (fn [[s cnts]]
[(str/join (interpose "?" (repeat 5 s))) [(str/join (interpose "?" (repeat 5 s)))
(vec (apply concat (repeat 5 cnts)))])) (vec (apply concat (repeat 5 cnts)))]))
(pmap #((make-anso) (first %) (second %) 0 0 0)) (pmap #(ans (first %) (second %)))
(reduce +)) (reduce +))