1

I have a group of N entities.
Is there any way for me to get all subgroups satisfy that the number of entities in each subgroup equals to M (N>M)?

I will give an example to clarify:

I have N = 5 integer (e.g: 1,3,4,6,8).
Is there any way to get all subgroups which contains L = 3 entities?
Those subgroups are {1,3,4}, {1,3,6}, {1,3,8}, {1,4,6}, {1,4,8}, {1,6,8}, {3,4,6}, ...

Seems that it must be a brute-force algorithm.

Thanks & regards

AbcAeffchen
  • 14,400
  • 15
  • 47
  • 66
wraith
  • 351
  • 3
  • 18

2 Answers2

1

Here is the pseudo-code for a recursive solution:

given_array[n]
current_combination[k]

void calculate( max_idx,  cur_idx, cur_count)
{
    if max_idx > cur_idx
        return
    if cur_count==k
        print current_combination
        return

    current_combination.add(given_array[cur_idx])
    calculate( max_idx, cur_idx+1, cur_count+1)
    current_combination.remove(given_array[cur_idx])


    calculate( max_idx, cur_idx+1, cur_count)

}

The first call of the function should be as follows:

calculate( n, 0, 0)
nitish712
  • 19,504
  • 5
  • 26
  • 34
0

Here is pseudo code for getting nCk

getCombinations(set[],i,x,k,buff[]) {

   if(i<k) {

     for(j=x;j<set.size();j++) {

           buff[i] = set[j];
           getCombinations(set,i+1,j+1,k,buff);
     }

   }

   else {   // print combination

        for(y=0;y<k;y++) {

            printf(set[buff[y]]);
        }

   }
}

Call :- getCombinations(set,0,0,k,new int[k]);
Vikram Bhat
  • 6,106
  • 3
  • 20
  • 19