2
$\begingroup$

I am looking for a nice way of constructing all possible pairings of a given list. Currently I am using the brute force approach of sieving the 2-partitions of all permutations.

Pairings[list_List]:=Block[{unis,ret},
 unis=Table[Unique[],Length[list]];
 ret=DeleteDuplicates@Map[Sort,Partition[#,{2}]&/@Permutations[unis],2];
 ret /. MapThread[Rule,{unis,list}]
];

Examples:

Pairings[{a,b,c,d,e,f}]

{{{a, b}, {c, d}, {e, f}}, {{a, b}, {c, e}, {d, f}}, {{a, b}, {c, f}, {d, e}}, {{a, c}, {b, d}, {e, f}}, {{a, c}, {b, e}, {d, f}}, {{a, c}, {b, f}, {d, e}}, {{a, d}, {b, c}, {e, f}}, {{a, d}, {b, e}, {c, f}}, {{a, d}, {b, f}, {c, e}}, {{a, e}, {b, c}, {d, f}}, {{a, e}, {b, d}, {c, f}}, {{a, e}, {b, f}, {c, d}}, {{a, f}, {b, c}, {d, e}}, {{a, f}, {b, d}, {c, e}}, {{a, f}, {b, e}, {c, d}}}

Pairings[{x,x,x,x}]

{{{x, x}, {x, x}}, {{x, x}, {x, x}}, {{x, x}, {x, x}}}

Although it gives the correct result, I am quite certain that this is not the optimal approach. Maybe there is something like this in the Combinatorica package, which I didn't find?

$\endgroup$
  • $\begingroup$ Tuples? $\endgroup$ – Oleksandr R. Jan 30 '16 at 21:18
  • $\begingroup$ ... doesn't do what I'm looking for. $\endgroup$ – murphy Jan 30 '16 at 21:31
  • $\begingroup$ is this a duplicate?: mathematica.stackexchange.com/q/78291/5478 $\endgroup$ – Kuba Jan 30 '16 at 21:48
  • $\begingroup$ @Kuba I don't see how that applies here (though it may) but this is easily answered by an earlier post, now marked as the original. $\endgroup$ – Mr.Wizard Jan 30 '16 at 21:51
  • $\begingroup$ @Mr.Wizard yep, that's better. $\endgroup$ – Kuba Jan 30 '16 at 21:52
0
$\begingroup$

This did turn out somewhat clumsy, but it avoids the n! complexity of Permutations

f[c_, {}] = c;
f[c_, s_] := g[c, First[s], Rest[s]]
g[c_, a_, b_] := Sequence @@ MapIndexed[f[Append[c, {a, #}], Delete[b, First[#2]]] &, b]
h[L_] := {f[{}, L]}

h[{a, b, c, d, e, F}]
(*{{{a, b}, {c, d}, {e, F}}, {{a, b}, {c, e}, {d, F}}, {{a, b}, {c, F},
   {d, e}}, {{a, c}, {b, d}, {e, F}}, {{a, c}, {b, e}, {d, F}}, {{a, c}, {b, F}, {d, e}},
   {{a, d}, {b, c}, {e, F}}, {{a, d}, {b, e}, {c, F}}, {{a, d}, {b, F}, {c, e}}, {{a, e}, {b, c}, {d, F}}, {{a, e},
   {b, d}, {c, F}}, {{a, e}, {b, F}, {c, d}}, {{a, F}, {b, c}, {d, e}}, {{a, F}, {b, d},
   {c, e}}, {{a, F}, {b, e}, {c, d}}}*)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.