General Question

PrettyDepressed's avatar

How can I write a program to generate all partitions of a set?

Asked by PrettyDepressed (12points) December 4th, 2010 from iPhone

I’m writing a program that does a whole bunch of set theory stuff to make my life easier, and I want it to generate all subsets of a list of elements. I’m looking for some kind of recursive solution…one that could ideally be contained in a single function or something. I know I’m like right on top of a solution, but for some reason I just can’t seem to carry it out.

For reference: http://en.wikipedia.org/wiki/Partition_of_a_set

Observing members: 0 Composing members: 0

4 Answers

ratboy's avatar

Do you want to generate all subsets, or all partitions?

LostInParadise's avatar

Come up with some order for the set. Going from first element to the next to last, either include just the element or include the element followed by a partition symbol. The last element is always included without a partition symbol after it. That gives the 2^(n-1) partitions. Writing a recursive program to do that should be fairly straightforward.

roundsquare's avatar

Something like this:

Subsets(Old, New)
{
If New is empty
print Old
Else
{
x = first element of New
Subsets(Old, New – x)
Subsets(Old + x, New – x)
}
}

Subsets(Empty Set, Original Set)

Urgh, tabbing not working. Oh well, its not too hard to figure out anyway.

PrettyDepressed's avatar

I did mean all partitions; I’ve already written a generator for subsets. I’d like to thank everyone for their help…I’m feeling so great now that I’ve figured out a solution. You guys helped me get thinking in the right direction…I am forever indebted :)

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther