Skip to content

Instantly share code, notes, and snippets.

@gzmask
Last active August 29, 2015 14:07
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 gzmask/50a4ae3e6ef11f331dd4 to your computer and use it in GitHub Desktop.
Save gzmask/50a4ae3e6ef11f331dd4 to your computer and use it in GitHub Desktop.
Counting Change Combinations codewars
(ns count-change)
(defn cart [colls]
(if (empty? colls)
'(())
(for [x (first colls)
more (cart (rest colls))]
(cons x more))))
(defn noseq? [x]
(number? (first x)))
;(defn compress [s]
;(filter noseq?
; (rest (tree-seq (complement noseq?) seq s))))
(defn compress [s]
(prn (pr-str "before: " s))
(let [l (map #(cond
(number? %) (list (list %))
(number? (first %)) (list %)
(number? (first (first %))) %
:else %) s)]
(prn (pr-str "middle: " l))
(do (prn (pr-str "after: " (apply concat l))) (apply concat l))
))
(defn selection [times coll] (cart (take times (repeat coll))))
(defn count-change
[money coins]
(cond
(> (count (filter (fn [c] (< c 0)) coins)) 0) 0
(= 0 money) 1
(empty? coins) 0
(< money (apply min coins)) 0
:else
(time
(let [coins (distinct (filter (fn [c] (<= c money)) coins))
dd (prn (pr-str coins))
n (quot money (apply min coins))
sets (time (doall (for [t (range 1 (inc n))]
(selection t coins))))
set (time (doall (distinct (map sort (compress (apply conj (map list coins) sets))))))
res (time (doall (map #(if (= money (apply + %)) 1 0) set)))
]
(apply + res)
))))
(ns count-change-test
(:require [clojure.test :refer :all]
[count-change :refer [count-change]]))
(deftest Testing...
(testing "(count-change 1 [1,2,3]) ; => 1"
(is (= (count-change 1 [1,2,3]) 1)))
(testing "(count-change 4 [1,2]) ; => 3"
(is (= (count-change 4 [1,2]) 3)))
(testing "(count-change 10 [5,2,3]) ; => 4"
(is (= (count-change 10 [5,2,3]) 4)))
(testing "(count-change 11 [5,7]) ; => 0"
(is (= (count-change 11 [5,7]) 0)))
(testing "(count-change 2 [1,2,3]) ; => 2"
(is (= (count-change 2 [1,2,3]) 2)))
(testing "count-change 5 [7 1 2 9 10]) ; => 3"
(is (= (count-change 5 [7 1 2 9 10]) 3)))
(testing "count-change 18 [4 6 3 10]) ; => 7"
(is (= (count-change 18 [4 6 3 10]) 7)))
(testing "(count-change 1 []) ; => 0"
(is (= (count-change 1 []) 0))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment