Permalink
Browse files

Traverse all items instead of stopping when current item does not fit…

… in knapsack
  • Loading branch information...
1 parent edc0099 commit bd6f25b1a1e5da02d09af8c481a58b4c55b6d15e @tsu tsu committed Mar 4, 2011
Showing with 22 additions and 9 deletions.
  1. +7 −6 src/lol/algorithm.clj
  2. +15 −3 test/lol/algorithm_test.clj
View
@@ -15,13 +15,14 @@
(defn fill-knapsack
([items limits] (fill-knapsack items limits []))
([items limits knapsack]
- (let [item (first items)
- new-limits (substract-from-limits limits item)]
- (if (or (some #(< % 0) new-limits) (empty? items))
- knapsack
- (recur (rest items) new-limits (cons item knapsack))))))
+ (if (empty? items)
+ knapsack
+ (let [item (first items)
+ new-limits (substract-from-limits limits item)]
+ (if (some (fn [x] (< x 0)) new-limits)
+ (recur (rest items) limits knapsack)
+ (recur (rest items) new-limits (cons item knapsack)))))))
(defn items-to-id-list
[items]
(map #(:id %) items))
-
@@ -18,10 +18,22 @@
'(15 31 7))))
(deftest test-fill-knapsack
- (let [items [{:id "1" :weight [642, 452] :value 593},{:id "2" :weight [62, 152] :value 93}]
+ (let [items [{:weight [642, 452]},
+ {:weight [62, 152]}]
limits [700 500]]
- (is (= [{:id "1" :weight [642, 452] :value 593}] (fill-knapsack items limits)))))
+ (is (= [{:weight [642, 452]}] (fill-knapsack items limits))))
+ (let [items [{:weight [642, 452]},
+ {:weight [62, 152]}]
+ limits [600 500]]
+ (is (= [{:weight [62, 152]}] (fill-knapsack items limits))))
+ (let [items [{:weight [642, 452]},
+ {:weight [28, 152]},
+ {:weight [62, 152]},
+ { :weight [621, 152]}]
+ limits [500 500]]
+ (is (= [{:weight [62, 152]},
+ {:weight [28, 152]},] (fill-knapsack items limits)))))
(deftest test-items-to-id-list
(let [items [{:id "3"} {:id "12"} {:id "57"} {:id "1"}]]
- (is (= ["3" "12", "57" "1"] (items-to-id-list items)))))
+ (is (= ["3" "12", "57" "1"] (items-to-id-list items)))))

0 comments on commit bd6f25b

Please sign in to comment.