Skip to content

Instantly share code, notes, and snippets.

@hadielmougy
Last active September 2, 2016 01:05
Show Gist options
  • Save hadielmougy/e4526cce2cdf9467a25a3c80dd79e94e to your computer and use it in GitHub Desktop.
Save hadielmougy/e4526cce2cdf9467a25a3c80dd79e94e to your computer and use it in GitHub Desktop.
(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