[p10] failed attempts for part 2

master
Jacopo De Simoi 3 months ago
parent 317878ed22
commit 9628410549
  1. 16
      lib/lib-advent.org
  2. 65
      p10/p10.org

@ -81,10 +81,14 @@
Add this function as an ~:around~ advice to any function to have its Add this function as an ~:around~ advice to any function to have its
results cached in ~cache~. The symbol ~cache~ should be already bound results cached in ~cache~. The symbol ~cache~ should be already bound
#+begin_src emacs-lisp #+begin_src emacs-lisp
(defun cache-result (fun &rest r) (defun cache-result (fun &rest r)
(let ((c (assoc (cons fun r) cache))) (let ((c (assoc (cons fun r) cache)))
(if c (cdr c) (if c (cdr c)
(let ((res (apply fun r))) (let ((res (apply fun r)))
(push (cons (cons fun r) res) cache) (push (cons (cons fun r) res) cache)
res )))) res ))))
(defun memoize (fun)
(setq cache nil)
(advice-add fun :around 'cache-result))
#+end_src #+end_src

@ -2,7 +2,7 @@
#+begin_src emacs-lisp :results none #+begin_src emacs-lisp :results none
(with-temp-buffer (with-temp-buffer
(insert-file-contents "input-test") (insert-file-contents "input")
(advent/replace-multiple-regex-buffer (advent/replace-multiple-regex-buffer
'(("," . " ") '(("," . " ")
("^" . "(") ("^" . "(")
@ -47,4 +47,65 @@ for part 1 we do not need the last item
#+end_src #+end_src
#+RESULTS: #+RESULTS:
: 7 : 404
This approach blows the stack
#+begin_src emacs-lisp
(setq machines (--map (-rotate 1 (cdr it)) data))
(defun apply-button (joltage button)
(--map-indexed (if (-contains-p button it-index) (- it 1) it) joltage))
(defun good-buttons (machine)
(-filter (lambda (button) (--every (< 0 (nth it (car machine))) button)) (cdr machine)))
(defun solve-machines (machines)
(-mapcat (lambda (machine)
(if (= 0 (-sum (car machine))) (list machine)
(--map (cons it (cdr machine)) (--map (apply-button (car machine) it) (good-buttons machine)))))
machines ))
(-iterate 'solve-machines (list (car machines)) 19)
#+end_src
Instead, go depth first and memoize for the win
#+begin_src emacs-lisp
(setq machines (--map (-rotate 1 (cdr it)) data)
machines (--map (cons (car it) (--sort (> (length it) (length other)) (cdr it))) machines))
(defun apply-button (joltage button)
(--map-indexed (if (-contains-p button it-index) (- it 1) it) joltage))
(defun good-buttons (machine)
(-filter (lambda (button) (--every (< 0 (nth it (car machine))) button)) (cdr machine)))
(defun or-min (l)
(when l (-min l)))
(defun nil-1+ (l)
(when l (1+ l)))
(defun solve-machine (machine)
(when machine
(if (= 0 (-sum (car machine))) 0
(nil-1+ (solve-machine (-first 'solve-machine (--map (cons it (cdr machine)) (--map (apply-button (car machine) it) (good-buttons machine)))))))))
(memoize 'solve-machine)
(let ((a))
(setq num 0
res nil)
(--each machines (progn (message (format "%d" (setq num (1+ num))))
(push (solve-machine it) res)))
(-sum res))
(cadr machines)
(solve-machine (cadr machines))
(length machines)151
#+end_src
#+RESULTS:
: 33

Loading…
Cancel
Save