Knapsack problem/Continuous: Difference between revisions

Line 354:
Take 3.5 of :welt
Total Value is: 349.3783783783784
</pre>
 
===Alternate Version===
<lang Clojure>
(def items
[{:name "beef" :weight 3.8 :price 36}
{:name "pork" :weight 5.4 :price 43}
{:name "ham" :weight 3.6 :price 90}
{:name "graves" :weight 2.4 :price 45}
{:name "flitch" :weight 4.0 :price 30}
{:name "brawn" :weight 2.5 :price 56}
{:name "welt" :weight 3.7 :price 67}
{:name "salami" :weight 3.0 :price 95}
{:name "sausage" :weight 5.9 :price 98}])
 
(defn per-kg [item] (/ (:price item) (:weight item)))
 
(defn rob [items capacity]
(let [best-items (reverse (sort-by per-kg items))]
(loop [items best-items room capacity total 0 instr ""]
(let [x (first items)]
(if (< (:weight x) room)
(recur (rest items)
(- room (:weight x))
(+ total (:price x))
(str instr "Take all " (:name x) "\n"))
(format "%sTake %.1f kg of %s\nTotal: %.2f"
instr room (:name x) (+ total (* room (per-kg x)))))))))
 
(print (rob items 15))
</pre>