Skip to content

Instantly share code, notes, and snippets.

@yosu
Created February 23, 2016 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yosu/42f41534dfeacc1b8b48 to your computer and use it in GitHub Desktop.
Save yosu/42f41534dfeacc1b8b48 to your computer and use it in GitHub Desktop.
5.10 Dynamic Programming: The Knapsack Problem - Introduction to Algorithms by Udi Manber
import Data.Array
knapsack :: [Int] -> Int -> Bool
knapsack xs cap = table!(cap, n)
where
n = length xs
ks = listArray (1, n) xs
table = array ((0,0), (cap, n)) $
[((k, 0), k == 0) | k <- [0..cap]] ++
[((k, i), ans k i) | k <- [0..cap], i <- [1..n]]
ans k i = (k - ks!i >= 0 && table!(k - ks!i, i-1)) || table!(k, i-1)
weights = [2, 3, 5, 6]
capacity = 11
main :: IO()
main = do
print $ knapsack weights capacity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment