From 43c9d643185163b1edeebc5750383e8b1f762523 Mon Sep 17 00:00:00 2001 From: Jacopo De Simoi Date: Wed, 14 May 2025 11:18:35 -0400 Subject: [PATCH] [p19] Implement caching as an advice --- p19/p19.org | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/p19/p19.org b/p19/p19.org index ee58125..7c9c35d 100644 --- a/p19/p19.org +++ b/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