Created
February 23, 2016 10:38
-
-
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
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
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