Archive for March, 2012

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

Programming Praxis – Balanced Delimiters

March 2, 2012

In today’s Programming Praxis exercise, our goal is to determine whether the delimiters in a given string are balanced. Let’s get started, shall we?

The exercise mentions that parser generators are useful for this exercise, but since the grammar isn’t very complicated I’m just going to use the straightforward method of pushing the delimiters onto a stack.

balanced :: String -> Bool
balanced = f [] where
    f bs       [] = null bs
    f bs       ('\\':_:cs) = f bs cs
    f (b:bs)   (c   :  cs) | lookup b pairs == Just c           = f bs cs
                           | elem b "'\""                       = f (b:bs) cs
    f bs       (c   :  cs) | any (\(a,b) -> elem c [a,b]) pairs = f (c:bs) cs 
                           | otherwise                          = f bs cs
    pairs = [('(', ')'), ('[', ']'), ('{', '}'), ('\'', '\''), ('"', '"')]

Some tests to see if everything is working properly:

main :: IO ()
main = do print . and $ map balanced ["", "abc", "()", "[[[]]]", "'('", "\\(()"]
          print . and $ map (not . balanced) ["(", "([)]", "'{'}", "\\()"]