Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

The Stirling number of the second kind is the number of ways to partition a set of $n$ objects into $k$ non-empty subsets. In Mathematica, this is implemented as StirlingS2. How can I enumerate all the sets? Ideally I would like to get a list of lists, where each list contains $k$ lists.

The question Partition a set into subsets of size k seems relevant.

share|improve this question
1  
Related: (8528) –  Mr.Wizard Feb 16 '13 at 1:18
add comment

2 Answers 2

up vote 6 down vote accepted
<< Combinatorica`
KSetPartitions[{a, b, c}, 2]
(*
  {{{a}, {b, c}}, {{a, b}, {c}}, {{a, c}, {b}}}
*)

 StirlingS2[3, 2]
 (* 3 *)
share|improve this answer
3  
Those who use Cobinatorica on 8 and 9 may be interested in this answer. This is how I usually load it now. –  Szabolcs Feb 16 '13 at 2:07
1  
@Szabolcs Oh! Thanks for linking it. All those error msgs are creepy sometimes –  belisarius Feb 16 '13 at 2:23
add comment

This is faster than the Combinatorica function:

KSetP[{}, 0] = {{}};
KSetP[s_List, 0] = {};
KSetP[s_List, k_Integer] /; k > Length@s = {};
KSetP[s_List, k_Integer] /; k > 0 :=
 Block[{ikf, s1 = s[[1]]},
  ikf[set_] := Array[MapAt[#~Prepend~s1 &, set, #] &, Length@set];
  Join[
   Prepend[#, {s1}] & /@ KSetP[Rest@s, k - 1],
   Join @@ ikf /@ KSetP[Rest@s, k]
  ]
 ]

(r1 = KSetPartitions[Range@12, 4]) // Timing // First

(r2 = KSetP[Range@12, 4])          // Timing // First
1.529

1.139

The output is in a different order but it is equivalent:

Sort[Sort /@ r1] === Sort[Sort /@ r2]

True

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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