mirror of
https://github.com/Ajetski/advent-of-code.git
synced 2025-09-30 09:33:19 -09:00
add memoizing utils
This commit is contained in:
parent
1f82ebfc52
commit
31348da8d4
@ -46,6 +46,29 @@
|
||||
([f] #(reduce f %))
|
||||
([f init] #(reduce f init %)))
|
||||
|
||||
(defmacro mfn
|
||||
"like fn but memoizes return values, including recursive calls"
|
||||
[name arglist & body]
|
||||
`(let [dp# (atom {})
|
||||
f# (fn ~name ~arglist
|
||||
(or (@dp# [~@arglist])
|
||||
(let [res# ~@body]
|
||||
(swap! dp# assoc [~@arglist] res#)
|
||||
res#)))]
|
||||
f#))
|
||||
|
||||
(defmacro defmfn
|
||||
"like defn but for a memoized fn, see ajet.core/mfn"
|
||||
[name & args]
|
||||
`(def ~name (mfn ~name ~@args)))
|
||||
|
||||
(comment
|
||||
(map (static-fn Long/parseLong) ["123" "456"])
|
||||
input-cache)
|
||||
input-cache
|
||||
|
||||
(defmfn fib [x]
|
||||
(if (< x 2)
|
||||
x
|
||||
(+ (fib (dec x))
|
||||
(fib (- x 2)))))
|
||||
(fib 200N))
|
||||
|
@ -1,20 +1,19 @@
|
||||
(ns day12
|
||||
(:require
|
||||
[clojure.string :as str]
|
||||
[core :refer [get-puzzle-input]]))
|
||||
[core :refer [get-puzzle-input mfn]]))
|
||||
|
||||
(defn parse-line [line] (-> (str/split line #" ")
|
||||
(update 1 #(->> (str/split % #",")
|
||||
(mapv parse-long)))))
|
||||
|
||||
(defn ans [dots blocks]
|
||||
(let [dp (atom {})
|
||||
(let
|
||||
[len-blocks (count blocks)
|
||||
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))
|
||||
(mfn f [i bi current]
|
||||
(let [dot-i (when (< i (count dots)) (get dots i))]
|
||||
(if (= i (count dots))
|
||||
(cond (and (= bi len-blocks)
|
||||
(= current 0))
|
||||
1
|
||||
@ -24,27 +23,25 @@
|
||||
:else
|
||||
0)
|
||||
(->> [\. \#]
|
||||
(map #(if (or (= dot_i %)
|
||||
(= dot_i \?))
|
||||
(map #(if (or (= dot-i %)
|
||||
(= dot-i \?))
|
||||
(cond (and (= % \.)
|
||||
(= current 0))
|
||||
(f dots blocks (inc i) bi 0)
|
||||
(f (inc i) bi 0)
|
||||
|
||||
(and (= % \.)
|
||||
(> current 0)
|
||||
(< bi len-blocks)
|
||||
(= (get blocks bi) current))
|
||||
(f dots blocks (inc i) (inc bi) 0)
|
||||
(f (inc i) (inc bi) 0)
|
||||
|
||||
(= % \#)
|
||||
(f dots blocks (inc i) bi (inc current))
|
||||
(f (inc i) bi (inc current))
|
||||
|
||||
:else 0)
|
||||
0))
|
||||
(reduce +)))]
|
||||
(swap! dp assoc [i bi current] v)
|
||||
v)))]
|
||||
(f dots blocks 0 0 0)))
|
||||
(reduce +)))))]
|
||||
(f 0 0 0)))
|
||||
|
||||
;; part 1
|
||||
(->> (get-puzzle-input 12)
|
||||
|
Loading…
x
Reference in New Issue
Block a user