Skip to content

Instantly share code, notes, and snippets.

@brpxqzme
Created January 31, 2014 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brpxqzme/5d7c3fa70dfff0962232 to your computer and use it in GitHub Desktop.
Save brpxqzme/5d7c3fa70dfff0962232 to your computer and use it in GitHub Desktop.
Coding for Interviews Issue #18 challenge: dynamic programming
(defun change-combinations (amount denominations)
"Return the number of (orderless) ways change can be made for integer AMOUNT
given a list of integer DENOMINATIONS."
(let ((dyntable (make-array (1+ amount) :initial-element 0)))
(setf (elt dyntable 0) 1)
(loop for denom in denominations
do (loop for dyndex from denom to amount
do (incf (elt dyntable dyndex)
(elt dyntable (- dyndex denom)))))
(elt dyntable amount)))
(defun csv-to-ints (csvstring)
"Return a list of integers given a string of comma-separated values.
Input presumed valid (whitespace is okay)."
(let ((strvals (loop for i = 0 then (1+ j)
as j = (position #\, csvstring :start i)
collect (subseq csvstring i j)
while j)))
(mapcar #'parse-integer strvals)))
(let ((coins (csv-to-ints (read-line)))
(amount (parse-integer (read-line))))
(print (change-combinations amount coins)))
@brpxqzme
Copy link
Author

brpxqzme commented Feb 1, 2014

(In practice, though, you'd probably prefer to install CL-UTILITIES and use SPLIT-SEQUENCE to get that list, and maybe do more string cleanup.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment