2

The method I'm trying to implement is like

/*
    e.g. {1, 2, 3}, k = 2

    ---> 

        [ (), () ],
        [ (1), () ],
        [ (), (1) ],
        [ (2), () ],
        [ (), (2) ],
        [ (3), () ],
        [ (), (3) ],
        [ (1), (2) ],
        [ (2), (1) ],
        [ (1), (3) ],
        [ (3), (1) ],
        [ (2), (3) ],
        [ (3), (2) ],
        [ (1,2), () ],
        [ (2,3), () ],
        [ (1,3), () ],
        [ (), (1,2) ],
        [ (), (1,3) ],
        [ (), (2,3) ],
        [ (1,2), (3) ],
        [ (2,3), (1) ],
        [ (1,3), (2) ],
        [ (3), (1,2) ],
        [ (1), (2,3) ],
        [ (2), (1,3) ],
        [ (1,2,3), () ],
        [ (), (1,2,3,) ]

*/

    public static List<List<T>> SpecialPartition<T>(this List<T> source, int k)
    {
        throw new NotImplementedException();
    }

I'm first wondering whether there's some known (Donald Knuth?) algorithm for doing this. Note how the order of the buckets matters, e.g. I consider (1,2), (3) and (3), (1,2) as separate results.

user7127000
  • 3,143
  • 6
  • 24
  • 41

1 Answers1

2

Note that every element could occupy one of (K+1) places (K buckets and one place out of any bucket).

So there are M=(K+1)^N combinations (here (2+1)^3=27 variants) and every number in range 0..M-1 corresponds to unique combination (one-to-one mapping).

So simple way to generate all combinations is to make loop for range 0..M-1 and represent loop counter in (K+1)-ary numeral system

for C = 0..M-1
   d = C
   for i = 0..N-1
     Bucket for i-th element = d %% (K+1)
     d = d / (K+1)

For example, 2110=2103 might be mapped: the first element in the 2nd bucket, second element in the 1st bucket, and the third element is off: [ (2), (1) ]

1610=1213: [ (1,3), (2) ]

MBo
  • 77,366
  • 5
  • 53
  • 86