Skip to content

Instantly share code, notes, and snippets.

@duarten
Created May 13, 2013 17:22
Show Gist options
  • Save duarten/5569918 to your computer and use it in GitHub Desktop.
Save duarten/5569918 to your computer and use it in GitHub Desktop.
Given a list of integrals, find all combinations of `n` values in the list such that their sum is `s`.
nSumCombinations :: (Integral a) => Int -> a -> [a] -> [[a]]
nSumCombinations _ _ [] = []
nSumCombinations 1 s xs = map (\x -> [x]) $ filter (== s) xs
nSumCombinations n s (x:xs) = (map (x:) $ nSumCombinations (n - 1) (s - x) xs) ++ (nSumCombinations n s xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment