Permutations and Combinations of a string

void permute(char *aHead,char *aTail)
{
// If there are no characters remaining in Head, i.e. we got one permutation
// So print it.
if(strlen(aHead) == 0){
printf(“%sn”,aTail);
return;
}

// Each time remove one character from Head and add it to the tail,
// and then recurse ……
for(int i=0;i< strlen(aHead);i++) int j=0,insertAt; char *NewTail = new char[100]; char *NewHead = new char[100]; // Create the arguments that need to be passed to the recursive function // Copy all the characters except the ith character to new array for(j=0,insertAt=0;j < strlen(aHead);j++) if(j!=i) NewHead[insertAt++] = aHead[j]; } NewHead[insertAt] = ''; // Append the excluded character to the tail strcpy(NewTail,aTail); int NewTailLen = strlen(NewTail); NewTail[NewTailLen] = aHead[i]; NewTail[NewTailLen+1] = ''; // Now recurse permute(NewHead,NewTail); } } void combinate(char *aHead,char *aTail) { // At each time, you have something in Tail, which is a combination of characters // So print it first // Difference 1 Print the tail always if(strlen(aTail) != 0) printf("%sn",aTail); // Now add other characters to the Tail, to make a new combination for(int i=0;i< strlen(aHead);i++) int j=0,insertAt; char *NewTail = new char[100]; char *NewHead = new char[100]; // Be careful, this is the difference for permutations and combinations // Difference 2, The new head will contain characters from i+1 as start // Because, it we include them also, it will cause repetition for(j=i+1,insertAt=0;j < strlen(aHead);j++) NewHead[insertAt++] = aHead[j]; NewHead[insertAt] = ''; strcpy(NewTail,aTail); int NewTailLen = strlen(NewTail); NewTail[NewTailLen] = aHead[i]; NewTail[NewTailLen+1] = ''; combinate(NewHead,NewTail); } }

Leave a Reply

Your email address will not be published. Required fields are marked *