Created
November 22, 2012 14:40
-
-
Save tzach/4131498 to your computer and use it in GitHub Desktop.
Two solution to the Coin Change Kata in Clojure
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
(ns coins.core) | |
;;; Solution I | |
;;; recursive, with coin hash as a parameter | |
(defn make-coins-rec [coins amount h] ;; all possible solutions in a nested list | |
"return all valid solutions" | |
(cond | |
(zero? amount) h | |
(pos? amount) (map #(make-coins-rec coins (- amount %) (update-in h [%] inc)) coins))) | |
(defn make-coins [coins amount] | |
"take the best solution" | |
(->> | |
(make-coins-rec coins amount (zipmap coins (repeat 0))) | |
flatten | |
(filter (comp not nil?)) | |
(sort-by #(reduce + (vals %))) | |
first | |
(filter (comp pos? val)) | |
(into {}) | |
)) | |
;; test | |
(make-coins [1 5 10 25] 18) | |
;;; Solution II | |
;;; recursive, with coin hash as a return value | |
(defn make-coins-rec2 [coins amount] | |
"return all valid solutions" | |
(cond | |
(zero? amount) (list {}) | |
(pos? amount) (for [c coins | |
sol (make-coins-rec2 coins (- amount c)) | |
:let [update-sol (update-in sol [c] (fnil inc 0))]] | |
update-sol) | |
)) | |
(defn make-coins2 [coins amount] | |
"take the best solution" | |
(apply min-key #(reduce + (vals %)) | |
(make-coins-rec2 coins amount))) | |
;; test | |
(make-coins2 [1 5 10 25] 18) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment