In [1]:
newtype Item = Item (Int, Int) deriving (Show)
weight :: Item -> Int
weight (Item (w, _)) = w
value :: Item -> Int
value (Item (_, v)) = v
In [2]:
import System.Random
sampleItems n = zipWith (curry Item) weights values
where
(weights, values) = splitAt n $ take (2*n) rseq
rseq = randomRs (1, 20) (mkStdGen 32345)
sampleItems 5
In [3]:
knapsack :: Int -> [Item] -> Int
knapsack _ [] = 0
knapsack w (x:xs)
| w < weight x = knapsack w xs
| otherwise = maximum ((knapsack w xs), (knapsack (w - weight x) xs) + value x)
sample = sampleItems 10000
knapsack 5000 sample
In [ ]:
maximum (2, 4)
In [ ]: