From 65a4aaeca350135f479f3bc435b61abeba313f9c Mon Sep 17 00:00:00 2001 From: Adam Jeniski Date: Thu, 14 Dec 2023 20:29:55 -0500 Subject: [PATCH] fix memoization --- 2023/src/day12.clj | 74 ++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/2023/src/day12.clj b/2023/src/day12.clj index 51a4dc8..0b8f4cb 100644 --- a/2023/src/day12.clj +++ b/2023/src/day12.clj @@ -7,53 +7,57 @@ (update 1 #(->> (str/split % #",") (mapv parse-long))))) -(defn make-anso [] - (with-local-vars - [ans (memoize - (fn f [dots blocks i bi current] - (let [len-blocks (count blocks) - dot_i (when (< i (count dots)) (get dots i))] - (if (= i (count dots)) - (cond (and (= bi len-blocks) - (= current 0)) - 1 - (and (= bi (dec len-blocks)) - (= current (get blocks bi))) - 1 - :else - 0) - (->> [\. \#] - (map #(if (or (= dot_i %) - (= dot_i \?)) - (cond (and (= % \.) - (= current 0)) - (f dots blocks (inc i) bi 0) +(defn ans [dots blocks] + (let [dp (atom {}) + f + (fn f [dots blocks i bi current] + (or (@dp [i bi current]) + (let [len-blocks (count blocks) + dot_i (when (< i (count dots)) (get dots i)) + v (if (= i (count dots)) + (cond (and (= bi len-blocks) + (= current 0)) + 1 + (and (= bi (dec len-blocks)) + (= current (get blocks bi))) + 1 + :else + 0) + (->> [\. \#] + (map #(if (or (= dot_i %) + (= dot_i \?)) + (cond (and (= % \.) + (= current 0)) + (f dots blocks (inc i) bi 0) - (and (= % \.) - (> current 0) - (< bi len-blocks) - (= (get blocks bi) current)) - (f dots blocks (inc i) (inc bi) 0) + (and (= % \.) + (> current 0) + (< bi len-blocks) + (= (get blocks bi) current)) + (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) - 0)) - (reduce +))))))] - (.bindRoot ans @ans) - @ans)) + :else 0) + 0)) + (reduce +)))] + (swap! dp assoc [i bi current] v) + v)))] + (f dots blocks 0 0 0))) +;; part 1 (->> (get-puzzle-input 12) (map parse-line) - (map #((make-anso) (first %) (second %) 0 0 0)) + (map #(ans (first %) (second %))) (reduce +)) +;; part 2 (->> (get-puzzle-input 12) (map parse-line) (mapv (fn [[s cnts]] [(str/join (interpose "?" (repeat 5 s))) (vec (apply concat (repeat 5 cnts)))])) - (pmap #((make-anso) (first %) (second %) 0 0 0)) + (pmap #(ans (first %) (second %))) (reduce +))