write a program to print combinations of string taken r at a time in c. According to wikipedia “a combination is a way of selecting items from a collection, such that (unlike permutations) the order of selection does not matter.” For example if given string is “1234” and if r is 2 then the output should be 12,13,14,23,24,34.

print combinations of string taken r at a time in cRecursive function to print combinations of string taken r at a time in c

#include<stdio.h>

void comb(int k, char *str, char *out, int strlen, int r, int next);

int main() {

	char string[] = "1234";
	// helper string for output
	char output[sizeof(string) - 1];
	int r = 2;
	// call comb
	comb(0, string, output, sizeof(string) - 1, r, 0);

	return 0;
}

void comb(int k, char *str, char *out, int strlen, int r, int next) {
	// base case
	int i = 0;
	if (k == r) {
		for (i = 0; i < r; i++) {
			printf("%c", out[i]);
		}
		printf("\n");
		return;
	}
	for (i = next; i < strlen; i++) {
		out[k] = str[i];
		comb(k + 1, str, out, strlen, r, i + 1);
	}
}

The above will print all combination of r element from array or string “1234”. 

Ref:

http://mathworld.wolfram.com/Combination.html



Related Contents to follow