ruby_r
ruby_r

Reputation: 87

Combinations of elements in an array

I'm trying to write a C program to find all the combinations of an given array and a specified length. This is what I've done so far..

#include <stdio.h>

void com(int* a, int* t, int len, int i) {

    int j, k;

    if(len == 0) {

        for(k=0;k<3;k++) {
            printf("%d  ",t[k]);
        }

        printf("\n");
        return;
    }

    for(j = i ; j <= 4-len ; j++) {  // 4 = original array size 
        t[3-len] = a[j];
        com(a,t,len-1,i+1);
    }
}

main() {

    int t[3];
    com((int[]){4,1,3,2},&t[0],3,0); // 3 = combination length
}

The problem in this code is that it has no option to skip duplicates, repetitions of combination. e.g for the array {1,2,3,4} it generates

1  2  3  
1  2  4  
1  3  3  
1  3  4  
2  2  3  
2  2  4  
2  3  3  
2  3  4 

but it was supposed to generate

1 2 3
1 2 4
1 3 4
2 3 4

What can I do for that? I'm not sure how to do that. Any kind of help would be appreciated. Thanks.

Also, if there is an alternative and better optimized solution than this, feel free to share.

Upvotes: 0

Views: 557

Answers (2)

0xdeadbeef
0xdeadbeef

Reputation: 86

#include <stdio.h>


int check(int *t)
{
  int j,k;

    for(k=0;k<3;k++)
    {
              for(j=k+1;j<3;j++)
              {
                   if(t[k]==t[j])
                   return 0;
               }
    }
  return 1;
}

 void com(int* a, int* t, int len, int i) {

    int j, k;
    int comb=1;


    if(len == 0)
    {


     comb = check(t);

     if(comb)
      {

       for(k=0;k<3;k++) 
          {
            printf("%d  ",t[k]);
          }

        printf("\n");
       }
        return;

     }

    for(j = i ; j <= 4-len ; j++) {  // 4 = original array size

    t[3-len] = a[j];
    com(a,t,len-1,i+1);
    }
}

main() {

int t[3];
com((int[]){4,1,3,2},&t[0],3,0); // 3 = combination length
}

Sorry for bad editing..

Upvotes: 1

BLUEPIXY
BLUEPIXY

Reputation: 40155

sample to fix

void com(int *a, int *t, int len, int i){
    if(i == len){
        for(int k = 0; k < len; k++)
            printf("%d ", t[k]);
        printf("\n");
        return;
    }
    while(*a){
        t[i] = *a;
        com(++a, t, len, i+1);
    }
}

int main(void){
    int t[3];

    com((int[]){1,2,3,4, 0}, t, 3, 0);
    //                   ^end mark
    return 0;
}

Upvotes: 1

Related Questions