[p19] Implement caching as an advice

main
Jacopo De Simoi 10 months ago
parent dca203577b
commit 43c9d64318
  1. 38
      p19/p19.org

@ -14,10 +14,21 @@ First parse with regex to make into a list
(eval-buffer))
#+end_src
Here we define a caching advice; this implementation works under the
assumption that the original function accepts one string as a
parameter
#+begin_src emacs-lisp :results none
(setq cache nil)
(setq possible-cache nil
impossible-cache nil)
(defun cached (fun r)
(if (assoc-string r cache) (cdr (assoc-string r cache))
(let ((result (funcall fun r)))
(push (cons r result) cache)
result)))
#+end_src
Here we recur down the tree obtained by splitting with all possible
prefixes. This is for part 1
#+begin_src emacs-lisp
@ -25,13 +36,10 @@ prefixes. This is for part 1
(--map (substring word (length it)) (--filter (string-prefix-p it word) avail)))
(defun possible-p (word)
(and (not (-contains-p impossible-cache word))
(or (string= "" word)
(-contains-p possible-cache word)
(if (-any #'possible-p (suffixes word))
(push word possible-cache)
(push word impossible-cache)
nil ))))
(or (string= "" word)
(-any #'possible-p (suffixes word))))
(advice-add #'possible-p :around 'cached)
(length (-filter #'possible-p patterns))
#+end_src
@ -45,14 +53,10 @@ This is for part 2;
(--map (substring word (length it)) (--filter (string-prefix-p it word) avail)))
(defun possible-arrangements (word)
(if (-contains-p impossible-cache word) 0
(cond
((string= "" word) 1)
((assoc-string word possible-cache) (cdr (assoc-string word possible-cache)))
(t (let ((arrangements (-sum (-map #'possible-arrangements (suffixes word)))))
(if (= arrangements 0) (push word impossible-cache)
(push (cons word arrangements) possible-cache))
arrangements)))))
(if (string= "" word) 1
(-sum (-map #'possible-arrangements (suffixes word)))))
(advice-add #'possible-arrangements :around #'cached)
(-sum (-map #'possible-arrangements patterns))
#+end_src

Loading…
Cancel
Save