Files
grokking_algorithms/08_greedy_algorithms/Haskell/01_powerset-covering.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

33 lines
1.0 KiB
Haskell

import Control.Applicative
import Data.List
import qualified Data.Set as Set
import qualified Data.HashMap.Strict as Map
stationsMap = Map.fromList [
("kone", Set.fromList(["id", "nv", "ut"])),
("ktwo", Set.fromList(["wa", "id", "mt"])),
("kthree", Set.fromList(["or", "nv", "ca"])),
("kfour", Set.fromList(["nv", "ut"])),
("kfive", Set.fromList(["ca", "az"]))
]
statesNeeded = Set.fromList ["mt", "wa", "or", "id", "nv", "ut", "ca", "az"]
powerSet xs = foldl (\acc x -> acc ++ (map (\e -> x:e) acc)) [[]] xs
allStationCombinations = powerSet $ Map.keys stationsMap
coverage stationsMap stations = map (`Map.lookup` stationsMap) stations
stationsCoverage stations =
fmap (Set.size . (Set.intersection statesNeeded)) $
Just (foldl Set.union Set.empty ) <*>
(sequence (coverage stationsMap stations))
solution = foldl
(\x y -> if stationsCoverage x >= stationsCoverage y then x else y)
first
rest
where (first: rest) =
sortBy (\a b -> compare (length a) (length b)) $
(filter (not . null) allStationCombinations)