Skip to main content

list manipulation - Partition a set into subsets of size $k$


Given a set $\{a_1,a_2,\dots,a_{lk}\}$ 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:


$$\text{Partition 1: }\{1,2\},\{3,4\}$$ $$\text{Partition 2: }\{1,3\},\{2,4\}$$ $$\text{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