Programming Praxis – 4SUM

In today’s Programming Praxis exercise, our goal is to find four integers in a given list that sum up to a given target number. Let’s get started, shall we?

We use the same approach of storing pair sums as the given solution. We store them using the sum as the key, which means we can use an IntMap, which offers improved performance over a regular Map.

import qualified Data.IntMap as I

First we generate all the pairs, then we try to find two pairs that sum up to the given number.

sum4 :: Int -> [Int] -> [[Int]]
sum4 n xs = take 1 [p1++p2 | (s, p1) <- I.assocs pairs
                           , p2 <- maybe [] return $ I.lookup (n-s) pairs]
    where pairs = I.fromList [(a+b, [a,b]) | a <- xs, b <- xs]

Some tests to see if everything is working properly:

main :: IO ()
main = do print $ sum (head $ sum4 0 [2,3,1,0,-4,-1]) == 0
          print $ sum4 0 [1,2,3,4,5,6] == []
          print $ sum4 13 [1,2,3,4,5,6] == [[1,1,6,5]]
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: