Combinations

Finding the the desired number of combinations from any given set of items is quite helpful in solving various types of problems. The C code has been presented below.

The executable file can be downloaded from here : COMBINATIONS

#include "stdio.h"
void printc(int comb[], int k) {
	int i;
	printf("{");
	for (i = 0; i < k; ++i)
		printf("%d, ", comb[i] + 1);
	printf("\b\b}\n");
}

int next_comb(int comb[], int k, int n) {
	int i = k - 1;
	++comb[i];
	while ((i >= 0) && (comb[i] >= n - k + 1 + i)) {
		--i;
		++comb[i];
	}

	if (comb[0] > n - k)
		return 0;
	for (i = i + 1; i < k; ++i)
		comb[i] = comb[i - 1] + 1;

	return 1;
}

int main() {
	int n,i,k,comb[1000];
	printf("Enter total no. of items : ");
	scanf("%d",&n);
	printf("Enter the no. of combinations : ");
	scanf("%d",&k);
	printf("\nThe Combinations are :\n");
	for (i = 0; i < k; ++i)
		comb[i] = i;
	printc(comb, k);
	while (next_comb(comb, k, n))
		printc(comb, k);

	return 0;
}


Related Posts

  • Share/Bookmark
You can leave a response, or trackback from your own site.

Leave a Reply

| Shop Free Cellular Phones at Bestincellphones.com. | Thanks to Best CD Rates, iCellPhoneDeals.com Offers Best Cell Phone Deals. and Incinerador De Grasa