Programming Praxis – Subset Sum

In today’s Programming Praxis problem, our goal is to find all the subsets of a list that sum up to a given number. Let’s get started, shall we?

Like the provided Scheme solution we choose the simple approach of determining all the subsets and summing them up. The main difference is that instead of making a hash table to remove duplicate additions I just use a simple fold.

subsetSum :: Num a => a -> [a] -> [[a]]
subsetSum n xs = [ns | (total, ns) <- subsets xs, total == n] where
    subsets = foldr (\x a -> (x, [x]) : map (\(t, ns) -> (t+x, x:ns)) a ++ a) []

A quick test to see if everything is working properly:

main :: IO ()
main = print $ subsetSum 5842 [267, 439, 869, 961, 1000,
    1153, 1246, 1598, 1766, 1922] == [[869,961,1000,1246,1766]]
About these ads

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: