efficiently accumulating values
- From: liyer.vijay@xxxxxxxxx
- Date: 5 Jul 2006 22:07:37 -0700
Hi,
I have a small lisp program to solve the boggle puzzle
(http://weboggle.shackworks.com/) and it generates a lot of lists.
This is the main part of the solving code:
(defun find-words (matrix)
"Given MATRIX find all possible words."
(destructuring-bind (m n) (array-dimensions matrix)
;; Find words starting at every position in the matrix
(loop with result = ()
as i from 0 to (1- m)
do (loop as j from 0 to (1- n)
do (setq result (nconc result ; <-- major consing
(get-words matrix i j))))
finally (return result))))
(defun get-words (matrix i j)
"Find all possible words starting from MATRIX position I J"
(labels ((rec (i j prefix acc)
(loop for (ni nj) in (adjacent matrix i j)
as next = (aref matrix ni nj)
as word = (concatenate 'string prefix next)
if (and (>= (length word) *minimum-length*)
(wordp word))
do (push word acc)
when (prefixp word)
do (let ((old (aref matrix i j)))
(setf (aref matrix i j) 'nil
acc (rec ni nj word acc)
(aref matrix i j) old))
finally (return acc))))
(rec i j (aref matrix i j) '())))
;;;;;;;;
Running the problem as it is, takes 2.713 seconds. Throwing away the
results obtained takes only 0.176 seconds. I changed find-words to
(defun find-words (matrix)
"Given MATRIX find all possible words."
(destructuring-bind (m n) (array-dimensions matrix)
(loop with result = (make-hash-table)
as i from 0 to (1- m)
do (loop as j from 0 to (1- n)
;; Find words starting at every position in the
matrix
do (loop as word in (get-words matrix i j)
do (setf (gethash word result) t)))
finally (return (loop as key being the hash-key in result
collect key)))))
This takes 1.786 seconds.
Is there an efficient way to accumulate values in lisp? I translated
this program almost sexp by sexp to Python and that runs in 0.61
seconds and in 0.49 seconds discarding the results.
Lisp is clearly faster except for the consing part. Any suggestions
on improving value accumulation welcome.
Cheers,
Vijay
Can we quote you on that?A long time ago, someone in the Lisp industry told me it was poor form
quote people; it suggests that they lack value.
-- Kent M Pitman <pitman@xxxxxxxxxxxxx> in comp.lang.lisp
.
- Follow-Ups:
- Re: efficiently accumulating values
- From: Kaz Kylheku
- Re: efficiently accumulating values
- From: liyer . vijay
- Re: efficiently accumulating values
- From: Ken Tilton
- Re: efficiently accumulating values
- Prev by Date: Re: ACL versus SBCL?
- Next by Date: Re: Minimal keywords needed for constructing a full CL system
- Previous by thread: Re: ACL versus SBCL?
- Next by thread: Re: efficiently accumulating values
- Index(es):
Relevant Pages
|