Function that prints out all the permutations of a string in C Programming

Started by Kalyan, Dec 01, 2008, 08:17 AM

Previous topic - Next topic

Kalyan

Function that prints out all the permutations of a string

For example, abc would give you abc, acb, bac, bca, cab, cba.

void PrintPermu (char *sBegin, char* sRest) {
int iLoop;
char cTmp;
char cFLetter[1];
char *sNewBegin;
char *sCur;
int iLen;
static int iCount;

iLen = strlen(sRest);
if (iLen == 2) {
iCount++;
printf("%d: %s%s\n",iCount,sBegin,sRest);
iCount++;
printf("%d: %s%c%c\n",iCount,sBegin,sRest[1],sRest[0]);
return;
} else if (iLen == 1) {
iCount++;
printf("%d: %s%s\n", iCount, sBegin, sRest);
return;
} else {
// swap the first character of sRest with each of
// the remaining chars recursively call debug print
sCur = (char*)malloc(iLen);
sNewBegin = (char*)malloc(iLen);
for (iLoop = 0; iLoop < iLen; iLoop ++) {
strcpy(sCur, sRest);
strcpy(sNewBegin, sBegin);
cTmp = sCur[iLoop];
sCur[iLoop] = sCur[0];
sCur[0] = cTmp;
sprintf(cFLetter, "%c", sCur[0]);
strcat(sNewBegin, cFLetter);
debugprint(sNewBegin, sCur+1);
}
}

}

void main() {
char s[255];
char sIn[255];
printf("\nEnter a string:");
scanf("%s%*c",sIn);
memset(s,0,255);
PrintPermu(s, sIn);
}


source : interviewghost