Re: Optimize lisp program
- From: Nicolas Neuss <lastname@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: 25 Nov 2006 14:13:35 +0100
OK, here you go. I doubt that you will have any speed problems with the
program below. What about a larger test?
Nicolas
(defstruct (coin (:type list))
price
weight)
(defun solve-piggy-bank (target-weight coins)
(let ((minimal-amount (make-array (1+ target-weight)
:initial-element nil)))
(setf (aref minimal-amount 0) 0)
(loop for weight from 0 upto target-weight
and amount across minimal-amount
when amount do
(loop for coin in coins
for new-weight = (+ weight (coin-weight coin))
and new-amount = (+ amount (coin-price coin))
when (<= new-weight target-weight) do
(let ((old-amount (aref minimal-amount new-weight)))
(when (or (null old-amount)
(> old-amount new-amount))
(setf (aref minimal-amount new-weight) new-amount)))))
(let ((amount (aref minimal-amount target-weight)))
(if amount
(format t "Minimal amount: ~A~%" amount)
(format t "Impossible!~%")))))
(solve-piggy-bank 31 '((2 3) (7 5)))
.
- Follow-Ups:
- Re: Optimize lisp program
- From: Nicolas Neuss
- Re: Optimize lisp program
- References:
- Optimize lisp program
- From: Anton V. Belyaev
- Re: Optimize lisp program
- From: Nicolas Neuss
- Re: Optimize lisp program
- From: Anton V. Belyaev
- Optimize lisp program
- Prev by Date: interactive
- Next by Date: how early to teach lisp at homeschool
- Previous by thread: Re: Optimize lisp program
- Next by thread: Re: Optimize lisp program
- Index(es):
Relevant Pages
|