c - Combinations of elements in an array -
i'm trying write c program find combinations of given array , specified length. i've done 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 = ; 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 code has no option skip duplicates, repetitions of combination. e.g array {1,2,3,4} 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 supposed generate
1 2 3 1 2 4 1 3 4 2 3 4
what can that? i'm not sure how that. kind of appreciated. thanks.
also, if there alternative , better optimized solution this, feel free share.
sample 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; }
Comments
Post a Comment