Given a set represented by a vector, e.g. [1,2,3]
, I want to iterate over all possible partitions (the order does not matter to me):
[[1], [2], [3]]
[[1,2], [3]]
[[1,3], [2]]
[[1], [2,3]]
[[1,2,3]]
I did not find a way to do this in the itertools
package, neither did I find anything elsewhere. The closest I have seen was this post on StackOverflow, however in that post not all partitions are generated, e.g. [[1,3],[2]]
in this case.
Is there maybe some existing package to do this? Or how could I achieve that?
Edit: To clarify:
- With "set" and "partition" I mean the mathematical notions, i.e.: a set X is a partition of a set A iff every element of X is a non-empty subset of A and every element of A appears in exactly one element of X.
- With "representation of a set by a vector" I mean a vector that contains each element of the set exactly once, in any order. In particular, it won't contain duplicate elements.
- What I actually want is an efficient iterator, which yields (a representation of) each possible partition exactly once. I.e. I am interested in some method
create_iterator(v: Vec<T>) -> impl Iterator<Item = Vec<Vec<T>>>
. I would prefer not to generate a vector of all partitions, since this has the drawbacks that it needs more space and, moreover, using the iterator I canbreak
, which can drastically reduce runtime. - An example use-case could look like this:
for x in create_iterator(vec![1,2,3]) {
println!("{:?}", x);
}