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
This commit is contained in:
committed by
Aditya Bhargava
parent
1ab56fce62
commit
542f4ab0a0
27
09_dynamic_programming/Haskell/01_knapsack-powerset.hs
Normal file
27
09_dynamic_programming/Haskell/01_knapsack-powerset.hs
Normal file
@@ -0,0 +1,27 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user