Let's say we have a Set S
which contains a few subsets:
- [a,b,c]
- [a,b]
- [c]
- [d,e,f]
- [d,f]
- [e]
Let's also say that S contains six unique elements: a, b, c, d, e
and f
.
How can we find all possible subsets of S
that contain each of the unique elements of S
exactly once?
The result of the function/method should be something like that:
[[a,b,c], [d,e,f]];
[[a,b,c], [d,f], [e]];
[[a,b], [c], [d,e,f]];
[[a,b], [c], [d,f], [e]].
Is there any best practice or any standard way to achieve that?
I would be grateful for a Pseudo-code, Ruby or Erlang example.
It sounds like what you are looking for are the partitions of a set/array.
One way of doing this is recursively:
A ruby implementation looks a little like
def partitions(x)
if x.length == 1
[[x]]
else
head, tail = x[0], x[1, x.length-1]
partitions(tail).inject([]) do |result, tail_partition|
result + partitions_by_adding_element(tail_partition, head)
end
end
end
def partitions_by_adding_element(partition, element)
(0..partition.length).collect do |index_to_add_at|
new_partition = partition.dup
new_partition[index_to_add_at] = (new_partition[index_to_add_at] || []) + [element]
new_partition
end
end