Last active
December 16, 2015 13:39
-
-
Save mihi-tr/5443534 to your computer and use it in GitHub Desktop.
The coin problem - as stated here: http://blog.jgc.org/2013/04/the-minimum-coin-problem-with-prize.html
This file contains hidden or 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
(def coins [2 1 1 0.5 0.5 0.2 0.2 0.2 0.1 0.05 0.05 0.02 0.02 0.01 0.01]) | |
(defn square [x] | |
(* x x)) | |
(defn distance | |
[x y] | |
(square (- x y))) | |
(defn fix-coin | |
[i coins fixed] | |
(let [coins (reverse (sort coins))] | |
(loop [coins coins | |
fixed fixed] | |
(if (and (first coins) (> (first coins) i)) | |
(recur (rest coins) (conj fixed (first coins))) | |
[coins, fixed])))) | |
(defn maximum-coins | |
[sum coins] | |
(let [sum (int (* 100 sum))] | |
(loop [cns (map #(int (* 100 %)) coins) | |
give '()] | |
(let [s (apply + (concat cns give)) | |
d (- s sum) | |
[cns give] (fix-coin d cns give) | |
cns (sort #(compare (distance d %1) (distance d %2)) | |
cns)] | |
(if (> (count cns) 0) | |
(recur (rest cns) give) | |
(map #(float (/ % 100)) give)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The initial version was simpler - this works however....