combinations

Print all combinations of M members of a set of N elements in a sequence such that each set can be obtained from the previous set by deleting one member and adding one member.

or Rather print nCr

Answer:


#include "stdio.h"
#include "iostream"
#include "algorithm"
#include "iterator"
#include "assert.h"
using namespace std;

int main(int argc, char *argv[])
{
const size_t n = atoi(argv[1]);
const size_t k = atoi(argv[2]);
cout << "N = " << n << " k = " << k << endl;
assert ( (k <= n) && (k > 0));
size_t *array = new size_t[n];
size_t up = 0;
size_t down = 0;
int i = 0;
// Initialize the arrray
for (i = 1; i <= n; ++i) array[i-1] = i;

for ( up = 0 , down = up+k-1; down < n; ++up , ++down)
{
printf(" \n up %d down %d \n", up, down);
for( i = down; i < n; ++i )
{
swap( array[down], array[i] );
//--- Print the combination ---
for(int k = up; k<=down; ++k)
cout << array[k] << " ";
cout << endl;
//--- End Print the combination ---
swap( array[i], array[down] );
}

}
return 0;
}



No comments: