work on p16 - more efficient

main
Jacopo De Simoi 11 months ago
parent 6d4495cf8c
commit a2ab388aff
  1. 34
      p16/p16.org

@ -4,7 +4,7 @@ Load map
#+begin_src emacs-lisp :results none
(require 'dash)
(with-temp-buffer
(insert-file-contents "input")
(insert-file-contents "input-test")
(goto-char (point-min))
(replace-regexp "^\\(#.*#\\)$" "\"\\1\"")
(goto-char (point-min))
@ -53,20 +53,28 @@ Define some aux functions
Now, explore the maze; this function returns a list of paths and the
associated scores;
#+begin_src emacs-lisp
(defun explore (p dir &optional score past)
"Explore the maze starting at position P and in the direction
(defun >nil (a b)
(when b
(or (not a) (> a b))))
(defun +nil (a b) ;we only need a binary operator
(when (not ))
)
(defun explore (p dir score &optional past)
"Explore the maze starting at position P and in the direction
DIR. Returns nil if we will dead-end or loop or the score
if we reach the end"
(if (eq (thing-at p) 'end) (list score)
(unless (-contains-p past p) ; loop
(let* ((forward-dirs (--filter (>= (dot it dir) 0)
'((0 1) (0 -1) (-1 0) (1 0))))
(acceptable-dirs (--filter (not (eq (thing-at (neighbour p it)) 'wall)) forward-dirs)))
(-mapcat (lambda (newdir)
(explore (neighbour p newdir) newdir
(+ score (if (equal newdir dir) 1 1001))
(cons p past)))
acceptable-dirs)))))
(if (eq (thing-at p) 'end) score
(unless (-contains-p past p) ; loop
(let* ((forward-dirs (--filter (>= (dot it dir) 0)
'((0 1) (0 -1) (-1 0) (1 0))))
(acceptable-dirs (--filter (not (eq (thing-at (neighbour p it)) 'wall)) forward-dirs)))
(-min-by #'>nil (-map (lambda (newdir)
(explore (neighbour p newdir) newdir
(+ score (if (equal newdir dir) 1 1001))
(cons p past)))
acceptable-dirs))))))
(explore start '(1 0) 0)
#+end_src

Loading…
Cancel
Save