Given a set {a1,a2,…,alk} and a positive integer l, how can I find all the partitions which includes subsets of size l in Mathematica? For instance, given {1,2,3,4}
and l=2
, the output should be:
Partition 1: {1,2},{3,4}
Partition 2: {1,3},{2,4}
Partition 3: {1,4},{2,3}
In Mathematica notation:
{
{{1,2},{3,4}},
{{1,3},{2,4}},
{{1,4},{2,3}}
}
Edit: Another example for l=3
, and {1,2,3,4,5,6}
:
{
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 4}, {3, 5, 6}},
{{1, 2, 5}, {3, 4, 6}},
{{1, 2, 6}, {3, 4, 5}},
{{1, 3, 4}, {2, 5, 6}},
{{1, 3, 5}, {2, 4, 6}},
{{1, 3, 6}, {2, 4, 5}},
{{1, 4, 5}, {2, 3, 6}},
{{1, 4, 6}, {2, 3, 5}},
{{1, 5, 6}, {2, 3, 4}}
}
Answer
Try with
partitions[list_, l_] := Join @@
Table[
{x, ##} & @@@ partitions[list ~Complement~ x, l],
{x, Subsets[list, {l}, Binomial[Length[list] - 1, l - 1]]}
]
partitions[list_, l_] /; Length[list] === l := {{list}}
The list must have a length multiple of l
Comments
Post a Comment