Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. {-# LANGUAGE ScopedTypeVariables #-}
  2. module Sums where
  3. import Data.IntMap.Lazy (IntMap)
  4. import Data.Maybe
  5. import Data.Monoid ((<>))
  6. import qualified Data.IntMap as IntMap
  7.  
  8. -- find all subsets which add upto the given size, given a function to
  9. -- extract the size. Only pick at most one element from each input subset.
  10. sums :: forall a.(a -> Int) -> Int -> [[a]] -> [[a]]
  11. sums size sum_ = fromMaybe [] . IntMap.lookup sum_ . sumsAux2
  12. where
  13. sumsAux2 :: [[a]] -> IntMap [[a]]
  14. sumsAux2 = foldr (\xs im -> foldr (sumsAux im) im xs) IntMap.empty
  15.  
  16. sumsAux :: IntMap [[a]] -> a -> IntMap [[a]] -> IntMap [[a]]
  17. sumsAux origIm x newIm
  18. | size x > sum_ = newIm
  19. | otherwise =
  20. IntMap.insertWith (<>) (size x) [[x]] $
  21. IntMap.foldrWithKey (\key val im2 ->
  22. if key + size x > sum_ then im2
  23. else IntMap.insertWith (<>) (key + size x)
  24. (map (x:) val) im2)
  25. newIm origIm
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement