fix memoization

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

View File

@ -7,13 +7,14 @@
(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]
(or (@dp [i bi current])
(let [len-blocks (count blocks) (let [len-blocks (count blocks)
dot_i (when (< i (count dots)) (get dots i))] dot_i (when (< i (count dots)) (get dots i))
(if (= i (count dots)) v (if (= i (count dots))
(cond (and (= bi len-blocks) (cond (and (= bi len-blocks)
(= current 0)) (= current 0))
1 1
@ -40,20 +41,23 @@
: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 +))