Knapsack problem/Continuous: Difference between revisions

Content added Content deleted
Line 373: Line 373:
(defn rob [items capacity]
(defn rob [items capacity]
(let [best-items (reverse (sort-by per-kg items))]
(let [best-items (reverse (sort-by per-kg items))]
(loop [items best-items room capacity total 0 instr ""]
(loop [items best-items cap capacity total 0 instr ""]
(let [x (first items)]
(let [x (first items)]
(if (< (:weight x) room)
(if (< (:weight x) cap)
(recur (rest items)
(recur (rest items)
(- room (:weight x))
(- cap (:weight x))
(+ total (:price x))
(+ total (:price x))
(str instr "Take all " (:name x) "\n"))
(str instr "Take all " (:name x) "\n"))
(format "%sTake %.1f kg of %s\nTotal: %.2f"
(format "%sTake %.1f kg of %s\nTotal: %.2f"
instr room (:name x) (+ total (* room (per-kg x)))))))))
instr cap (:name x) (+ total (* cap (per-kg x)))))))))


(print (rob items 15))
(print (rob items 15))