Files
grokking_algorithms/09_dynamic_programming/Haskell/01_knapsack-powerset.hs
Bijoy Thomas 542f4ab0a0 Added Haskell example for Dijkstras algorithm (#18)
* Adding binary search example for Haskell

* Adding selection sort example in Haskell

* Adding Haskell examples for chapter 3

* Adding examples for chapter 4

* Adding examples for chapter 5

* Adding git ignore

* Add Haskell example for BFS

* resetting

* Adding haskell example for dijkstras algorithm

* Adding Haskell example for chapter 8

* Adding power set based solution for set covering problem

* Adding Haskell examples for chap 9
2017-11-13 08:16:12 -08:00

28 lines
795 B
Haskell

import Control.Applicative
import Data.List
import qualified Data.Set as Set
import qualified Data.HashMap.Strict as Map
items = Map.fromList [
("stereo", (4, 3000)),
("laptop", (3, 2000)),
("guitar", (1, 1500))
]
value set = (a, b)
where
weightandvalues = (sequence $ map (`Map.lookup` items) set)
Just (a,b) = Just (foldl (\(a,b) (c,d) -> (a+c, b+d)) (0,0)) <*> weightandvalues
powerSet xs = foldl (\acc x -> acc ++ (map (\e -> x:e) acc)) [[]] xs
solution = foldl
(\acc v -> let
(firstweight, firstvalue) = value acc
(secondweight, secondvalue) = value v
in if firstweight <= 4 && firstvalue >= secondvalue then acc else if secondweight <= 4 then v else acc)
first
rest
where
(first: rest) = filter (not . null) $ powerSet $ (Map.keys items)