Thursday, January 24, 2013

Given a String of Length N, find all combinations of substrings of length k(Repetition Allowed)

Print all combination of given length k possible with characters available in a given string "S" with repetition in new lines.
Again an easy recursion problem.

void printAllCombinationsOfLengthK(char in[],int n,char* out,int k,int l){
	if(k==l){
		printf("%s\n",out);
		return;
	}
	for(int i=0;i<n;i++){
		out[l]=in[i];
		printAllCombinationsOfLengthK(in,n,out,k,l+1);
	}
}

int main(){
    ios_base::sync_with_stdio(false);
	
	char* a="abcdef";
	int k=3;
	char op[k]; // Output string of length K
	
	printAllCombinationsOfLengthK(a,strlen(a),op,k,0);

    system("PAUSE");
}

No comments:

Post a Comment