3

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.

Gennaro Arguzzi
  • 959
  • 6
  • 16

4 Answers4

4
ClearAll[addPair, pairPartitions]

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

pairPartitions[n_] := DeleteDuplicatesBy[Sort] @
  Nest[Catenate @* Map[addPair[n]], List /@ Thread[{1, Range[2, n]}], n/2 - 1]

Examples:

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

enter image description here

Length @ pairPartitions[#] & /@ {2, 4, 6, 8, 10, 12}
{1, 3, 15, 105, 945, 10395}
kglr
  • 394,356
  • 18
  • 477
  • 896
2

Too complex ,but work.

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

15

enter image description here

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}

cvgmt
  • 72,231
  • 4
  • 75
  • 133
2
ClearAll[twoPartitions]
twoPartitions[n_] := Select[Union@@# == Range[n]&]@Fold[Subsets, Range@n, {{2}, {n/2}}]

Examples:

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

enter image description here

Length @ twoPartitions[#] & /@ {2, 4, 6, 8, 10}
 {1, 3, 15, 105, 945}
kglr
  • 394,356
  • 18
  • 477
  • 896
1

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}
azerbajdzan
  • 15,863
  • 1
  • 16
  • 48