Skip to content

Instantly share code, notes, and snippets.

@amalloy
Forked from actsasbuffoon/calculate_change.clj
Created August 26, 2012 00:24
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 amalloy/3472749 to your computer and use it in GitHub Desktop.
Save amalloy/3472749 to your computer and use it in GitHub Desktop.
My first attempt at Clojure. Suggestions/criticism welcome.
(let [currency-values [[:hundreds 10000]
[:fifties 5000]
[:twenties 2000]
[:tens 1000]
[:fives 500]
[:ones 100]
[:quarters 25]
[:dimes 10]
[:nickels 5]
[:pennies 1]]]
(defn calculate-change [paid cost]
(loop [coins [], remaining (- cost paid), denoms currency-values]
(if-let [[[coin value] & denoms] (seq denoms)]
(let [num-coins (quot remaining value)]
(if (zero? num-coins)
(recur coins remaining denoms)
(recur (conj coins [num-coins coin])
(- remaining (* num-coins value))
denoms)))
coins)))
;; ...or...
(defn calculate-change [paid cost]
(remove (comp #{0} first)
(map :coins
(rest
(reductions (fn [{:keys [remaining]} [denom value]]
(let [num-coins (quot remaining value)]
{:remaining (- remaining (* num-coins value))
:coins [num-coins denom]}))
{:remaining (- cost paid)}
currency-values))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment