Advertisement
Guest User

knapsack.clj

a guest
Aug 12th, 2013
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn calc-max-value [i w items]
  2.   ;; if either num items or capacity is zero max value is zero!
  3.   (if (or (= i 0) (= w 0))
  4.     0
  5.     (let [curr-item (get items (- i 1))
  6.           prev-max-value (calc-max-value (- i 1) (- w (:weight curr-item)) items)
  7.           max-value-without-me (calc-max-value (- i 1) w items)
  8.           potential-value-with-me (+ (:value curr-item) prev-max-value)
  9.           ]
  10.       (if (<= (:weight curr-item) w)
  11.         ;; current item weight will not exceed knapsack capacity
  12.         ;; take the larger of value with current item and
  13.         ;; value without current item
  14.         (if (> potential-value-with-me max-value-without-me)
  15.           potential-value-with-me
  16.           max-value-without-me)
  17.  
  18.         ;; current item weight exceeds knapsack capacity so take
  19.         ;; max value without current item
  20.         max-value-without-me ))))
  21.  
  22. (defn solve-knapsack [n w items]
  23.   (let [find-max (memoize calc-max-value)]
  24.     (loop [i n
  25.            k w
  26.            knapsack []]
  27.       (let [curr-item (get items (- i 1))]
  28.         ;; base case, return the knapsack contents so far
  29.         (if (or (= 0 k) (= 0 i))
  30.           knapsack
  31.           (if (not= (find-max i k items) (find-max (- i 1) k items))
  32.             (recur (- i 1) (- k (:weight curr-item)) (conj knapsack curr-item))
  33.             (recur (- i 1) k knapsack )))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement