//generates all possible combinations of given n objects
//combination.c@standard c library(*SCL*) by ASHISH TIWARI
/*
You may print, store code from this program for your personal,
noncommercial use. By accessing this code, you agree not to reproduce, distribute,
display or transmit information from this code in any form or by any means without
the permission of ASHISH TIWARI, with this exception: You may occasionally reproduce,
distribute, display or transmit an insubstantial portion of the information, for a
noncommercial purpose, to a limited number of individuals. ASHISH TIWARI does not warrant
the accuracy, completeness, timeliness, merchantability or fitness for a particular purpose
of the cose,though every care has been taken in making this code and has been compiled
on standard gcc compiler provided by GNU. ASHISH TIWARI shall not be liable for any
errors or omissions in the information or decisions made or actions taken in reliance
on the code.

"*SCL*" is a registered trademark of ASHISH TIWARI, IITKGP.
All contents of "*SCL*" is copyright ©2000-.... ,ASHISH TIWARI, IITKGP
unless otherwise noted. Reproduction in part or in whole without
permission is expressly prohibited.
*/



#include<stdio.h>


void generate_comb(int n,int r);
long int comb(int n,int r);
long int itercomb(double n,double r);
double fac(double n);
main()
{
int n=15,r=8;
generate_comb(n,r);


}

void generate_comb(int n,int r)
{
long int ncr;
ncr=comb(n,r);
int* counter;
counter=(int*)malloc(r*sizeof(int));
int** store;
int i,j,k,l;
store=(int**)malloc(ncr*sizeof(int*));
for(i=0;i<ncr;i++)
store[i]=(int*)malloc(r*sizeof(int));

for(i=1;i<=r;i++)
counter[i-1]=i;
for(i=0;i<ncr;i++)
for(j=0;j<r;j++)
{
store[i][j]=counter[j];
if(j==r-1)
{
for(k=r-1;k>=0;k--)
{
if(counter[k]!=(n-(r-(k+1))))
{
counter[k]++;
for(l=k+1;l<r;l++)
counter[l]=counter[l-1]+1;
break;
}
else
continue;
}
}
else
continue;
}
for(i=0;i<ncr;i++)
{
for(j=0;j<r;j++)
{
printf("%d ",store[i][j]);
}
printf("\n");
}
}



long int comb(int n,int r)
{
if(r==0 || r==n)
return(1);
if(r==1)
return(n);
return(comb(n-1,r)+comb(n-1,r-1));
}

long int itercomb(double n,double r)
{
double i,j,k,l;
i=fac(n);
j=fac(r);
k=fac(n-r);
l=j*k;
return((long int)(i/l));
}

double fac(double n)
{
double fact=1;
double i;
for(i=n;i>1;i--)
{
fact=fact*i;
}
printf("%lf\n",fact);
return(fact);
}