Suppose I have a list of symbols like:
{a,b,c,d}
I would like to enumerate all possible binary associations (combining symbols and/or sublists pairwise):
{{{a,b},c},d}
{{a,b},{c,d}}
{a,{b,{c,d}}}
{{a,{b,c}},d}
{a,{{b,c},d}}
There should be altogether 5 solutions for this example. My question is how can I enumerate all such associations for a generic list?
I have tried
ReplaceList[{a,b,c,d},{u___,v_,w_,x___}:>{u,{v,w},x}]
But this only works for the first layer.
Answer
I propose a more compact approach
f[list__] := Join @@ ReplaceList[{list}, {x__, y__} :> Tuples@{f[x], f[y]}]
f[x_] := {x};
f[a, b, c, d] // Column
{a,{b,{c,d}}}
{a,{{b,c},d}}
{{a,b},{c,d}}
{{a,{b,c}},d}
{{{a,b},c},d}
One can note that the length of this list is the Catalan number
$$ C_n = \frac{1}{1+n}{2n\choose n} $$
Length[f @@ ConstantArray[a, 6]]
CatalanNumber[6 - 1]
WolframAlpha["answer to life the universe and everything"]
42
42
42
Comments
Post a Comment