Last active
September 2, 2016 01:05
-
-
Save hadielmougy/e4526cce2cdf9467a25a3c80dd79e94e to your computer and use it in GitHub Desktop.
This file contains 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 items [[1 2] [2 4] [3 6] [10 5]]) | |
(defn values [] (into [] ((fn [items] (for [i items] {:weight (first i) :value (last i)}))items))) | |
(defn knapsack [weight values] | |
(if | |
(empty? values) 0 ;; base case | |
(if (> (:weight (first values)) weight) | |
(knapsack weight (rest values)) ;; continue | |
(max | |
(+ (:value (first values)) (knapsack (- weight (:weight (first values))) (rest values))) | |
(knapsack weight (rest values)))))) ;; compare branches | |
(knapsack 12 (values)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment