I've written this program that writes all the combinations (without repetition) of n elements in groups of k.
I think the code is good, but I like to know if you have some better (or faster) solutions.
The elements to combine are always the number from 0 to n-1, the program calls a function (newCombo()
) for each generated combination.
EG: Using n=6 and k=4 the program generates the following output:
0 1 2 3
0 1 2 4
0 1 2 5
0 1 3 4
0 1 3 5
0 1 4 5
0 2 3 4
0 2 3 5
0 2 4 5
0 3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
The code is below:
#include <stdio.h>
void newCombo(int *a,int n,int k);
void newCombo(int *a,int n,int k)
{
int i;
for(i=0;i<k;i++)
printf("%d ",a[i]);
puts("");
}
int main(int argc,char *argv[])
{
int a[30];
int n,k,p;
do {
printf("Insert n and k - EG: 5 3: ");
if (scanf("%d %d",&n,&k)!=2)
return 1;
if (k>n)
puts("k shall be <= n !");
if (k==0 || n==0)
puts("k and n shall not be 0!");
if (k>30)
puts("k shall be <=30");
} while (k>n || k==0 || n==0 || k>30);
p=0;
a[0]=-1;
do {
if (++a[p]>n-k+p) {
p--;
} else {
if (p<k-1) {
a[p+1]=a[p];
p++;
} else {
newCombo(a,n,k);
}
}
} while(p>=0);
return 0;
}