# Finding all partitions (2 elements per subset) of a set composed of an even number of elements

I'd like to find all the partitions (each subset of a partition should contain 2 elements) of a set composed by an even number of elements. For example, given $$A=\lbrace 1,2,3,4,5,6 \rbrace$$, I'd like to see the partitions:

$$\lbrace \lbrace 1,2 \rbrace, \lbrace 3,4 \rbrace, \lbrace 5,6 \rbrace \rbrace \\ \lbrace \lbrace 1,3 \rbrace, \lbrace 2,4 \rbrace, \lbrace 5,6 \rbrace \rbrace \\ \ldots$$

etc.

• Perhaps Partition[#,2]&/@Permutations@Range@6? Commented Jan 19, 2022 at 14:11
• Hi @Hausdorff can you post an answer with the needed code please? Commented Jan 19, 2022 at 15:02

Too complex ,but work.

result6 =
Sort /@ (Map[
Sort] /@ (Partition[#, 2] & /@ Permutations[Range[6]])) //
DeleteDuplicates
result6//Length
Grid[result6, Dividers -> {False, All}]

15

result8 =
Sort /@ (Map[
Sort] /@ (Partition[#, 2] & /@ Permutations[Range[8]])) //
DeleteDuplicates;
reslut8//Length
Grid[Partition[result8, 3], Dividers -> {All, All}]

105

For general n=2k,the answer should be (n-1)!!,but I don't know how to list it in a simple way.

Table[(2 k - 1)!!, {k, 1, 5}]

{1, 3, 15, 105, 945}

• Hello @cvgmt thank you very much for your helpful answer. The second part of the code is about which case? Commented Jan 19, 2022 at 14:53
• @GennaroArguzzi For n=8 there are (n-1)!!=7!!=7*5*3*1=105 partitions. Commented Jan 19, 2022 at 14:55
• yes and also the result8 code. Commented Jan 19, 2022 at 14:55

addPair[n_][{parts : {_, _} ..}] := Append[{parts}, #] & /@
Subsets[Complement[Range @ n, parts], {2}]

pairPartitions[n_] := DeleteDuplicatesBy[Sort] @

Examples:

pairPartitions[6] // Grid[#, Dividers -> {None, All}]&

Length @ pairPartitions[#] & /@ {2, 4, 6, 8, 10, 12}
{1, 3, 15, 105, 945, 10395}
• perfect, very nice! Commented Jan 19, 2022 at 15:15
ClearAll[twoPartitions]
twoPartitions[n_] := Select[Union@@# == Range[n]&]@Fold[Subsets, Range@n, {{2}, {n/2}}]

Examples:

twoPartitions[6] // Grid[#, Dividers -> {None, All}]&

Length @ twoPartitions[#] & /@ {2, 4, 6, 8, 10}
{1, 3, 15, 105, 945}
• Ciao @kglr can you organize the result in a table as in the cvgmt answer please? Commented Jan 19, 2022 at 15:10

Something much more efficient with a brain teasing code.

Clear[pairs]
pairs[0] = {{}};
pairs[n_] :=
Flatten[(d |->
Prepend[Partition[Complement[Range[n], d][[Flatten@#]], 2],
d] & /@ pairs[n - 2]) /@ ({1, #} & /@ Rest@Range[n]), 1]

Timings:

Table[Length[pairs[n]] // Timing, {n, 0, 14, 2}] // Column

{0.,1}
{0.,1}
{0.,3}
{0.,15}
{0.015625,105}
{0.046875,945}
{0.625,10395}
{8.53125,135135}