-
-
Save amalloy/3472749 to your computer and use it in GitHub Desktop.
My first attempt at Clojure. Suggestions/criticism welcome.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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