Partition a set into subsets of size $k$
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
I believe this is correct. It is based on BellList
from Robert M. Dickau.
Module[{n = 4, q = 2, r, BellList},
r = n/q;
BellList[1] = {{{1}}};
BellList[n_Integer?Positive] :=
Join @@ (ReplaceList[#,
{{b___, {S : Repeated[_, {1, q - 1}]}, a___} :> {b, {S, n}, a},
{S : Repeated[_, {1, r - 1}]} :> {S, {n}}}
] & /@ BellList[n - 1]);
BellList[n]
]
You'll have to make sure n
is divisible by q
or adapt it to behave as you want. Also, this uses natural numbers for the set, but these in turn can be used as indices to extract elements from the working set.
Use Subsets
:
Subsets[{1, 2, 3, 4}, {2}]
Gives:
{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}}
Edit How about:
a = {1, 2, 3, 4};
DeleteDuplicates[Sort /@ (Sort /@ Partition[#, 2] & /@ Permutations[a, {4}])]
which outputs
{{{1, 2}, {3, 4}}, {{1, 3}, {2, 4}}, {{1, 4}, {2, 3}}}