# How to constrain the generation of all possible orderings?

Here is code from Simon Woods' answer for getting all possible weak (equal ranks allowed) orderings for $N=3$ objects:

 ClearAll[f]; SetAttributes[f, Orderless];
ReplaceList[f[a, b, c], f[a___, b___, c___] :> {{a}, {b}, {c}}] //
DeleteCases[#, {}, -1] & // Union // Column


It gives $13$ such orderings:

{{a, b, c}}
{{a}, {b, c}}
{{b}, {a, c}}
{{c}, {a, b}}
{{a, b}, {c}}
{{a, c}, {b}}
{{b, c}, {a}}
{{a}, {b}, {c}}
{{a}, {c}, {b}}
{{b}, {a}, {c}}
{{b}, {c}, {a}}
{{c}, {a}, {b}}
{{c}, {b}, {a}}


How can I modify this code for the case when not more than $2$ subsets are allowed? The desired output is:

{{a, b, c}}
{{a}, {b, c}}
{{b}, {a, c}}
{{c}, {a, b}}
{{a, b}, {c}}
{{a, c}, {b}}
{{b, c}, {a}}


I am trying to find way for doing such reductions in general $N$ and for any number of subsets-restriction.

-
Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Dr. belisarius Nov 26 '13 at 14:35

Here's how you can generalize the code for any $N$:

ClearAll@weakOrderings
weakOrderings[list_, n_Integer] :=
Block[{f, x = Table[Unique["x"], {n}]},
SetAttributes[f, Orderless];
With[{lhs = f @@ (Pattern[#, BlankNullSequence[]] & /@ x), rhs = List /@ x},
ReplaceList[f @@ list, lhs :> rhs] // DeleteCases[#, {}, -1] & // Union // Column
]
]


You can verify that it gives you the expected results:

-
Hm... No output gives. Sorry, I am null in Mathematica. Just copy-pasted your code and used Ctrl+Enter. – aeiklmkv Nov 26 '13 at 14:12
@aeiklmkv I showed how to call the function in the screenshot... – R. M. Nov 26 '13 at 14:14
@rm-rf Now I understand. It works. – aeiklmkv Nov 26 '13 at 14:24
@YvesKlett This is not my homework. I need it for statistical analysis of some experimental data. I am not lazy, just a beginner in Mathematica. – aeiklmkv Nov 26 '13 at 14:25
@aeiklmkv Please consider that there are quite a few students around trying to suck other user's time to get their homework done without effort. Try to differentiate your questions from theirs – Dr. belisarius Nov 26 '13 at 14:42
Needs["Combinatorica"]
f[l_List, n_Integer] := Flatten[Table[Union@Map[Sort,
Flatten[KSetPartitions[#, i] & /@ Permutations[l], 1], {2}], {i, n}], 1]

f[{a, b, c}, 2] // Column
(*
{{a,b,c}}
{{a},{b,c}}
{{b},{a,c}}
{{c},{a,b}}
{{a,b},{c}}
{{a,c},{b}}
{{b,c},{a}}
*)
f[{a, b, c}, 3] // Column
(*
{{a,b,c}}
{{a},{b,c}}
{{b},{a,c}}
{{c},{a,b}}
{{a,b},{c}}
{{a,c},{b}}
{{b,c},{a}}
{{a},{b},{c}}
{{a},{c},{b}}
{{b},{a},{c}}
{{b},{c},{a}}
{{c},{a},{b}}
{{c},{b},{a}}
*)
`
-