Skip to content

Instantly share code, notes, and snippets.

@tzach
Created November 22, 2012 14:40
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 tzach/4131498 to your computer and use it in GitHub Desktop.
Save tzach/4131498 to your computer and use it in GitHub Desktop.
Two solution to the Coin Change Kata in Clojure
(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