Posts Tagged ‘sums’

Programming Praxis – Partitions

May 11, 2012

In today’s Programming Praxis exercise, our goal is to write a function that gives all unique sums that produce a given number. Let’s get started, shall we?

The function is fairly trivial. We avoid duplicates by allowing only equal or decreasing series of numbers.

part :: Int -> [[Int]]
part 0 = [[]]
part n = [x:y | x <- [1..n], y <- part (n-x), [x] >= take 1 y]

A quick test to see if everything is working properly:

main :: IO ()
main = mapM_ print $ part 6

Programming Praxis – Subset Sum

March 27, 2012

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]]