Combinations of elements in an array

流过昼夜 提交于 2020-08-11 07:33:14

问题


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.


回答1:


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;
}



回答2:


#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..



来源:https://stackoverflow.com/questions/30253110/combinations-of-elements-in-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!