Programming Praxis – Partitions

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