I am trying to store the permutations generated by the recursive permutation function so that I can use them in main; however, I cannot figure how to get them to store correctly. I.E. when I run this function with a string AB, inside the recursive AB and BA gets printed but in main AB and AB again get printed.
Any suggestions on how to resolve this would be appreciated.
Thanks
Drew
#include <stdio.h>
void ListPermutations(char str[]);
void RecursivePermute(char str[], int k);
void ExchangeCharacters(char str[], int i, int j);
char** numPerms;
int ii = 0;
int main() {
int i = 0;
numPerms = calloc(sizeof(char *), (2));
for(i=0; i<2;i++)
numPerms[i] = calloc(sizeof(char), 2);
char word[20];
// Let the user enter a word to permute.
printf("Please enter a word you would like to permute.\n");
scanf("%s", word);
printf("\n");
// Print out the permutations.
ListPermutations(word);
printf("This should be the same as above but it is not\n");
for(i=0;i<2;i++)
printf("%s\n",numPerms[i]);
system("PAUSE");
return 0;
}
// Pre-condition: str is a valid C String.
// Post-condition: All permutations of str (assuming all distinct
// characters) will be printed.
void ListPermutations(char str[]) {
// Call the appropriate recursive function with the correct
// parameters.
RecursivePermute(str, 0);
}
// Pre-condition: str is a valid C String, and k is non-negative and
// less than or equal to the length of str.
// Post-condition: All of the permutations of str with the first k
// characters fixed in their original positions are
// printed. Namely, if n is the length of str, then
// (n-k)! permutations are printed.
void RecursivePermute(char str[], int k) {
int j;
// Base-case: Since all letters are fixed, we can ONLY print
// what's stored in str.
if (k == strlen(str)){
printf("%s\n", str);
numPerms[ii] = str;
ii++;
}
else {
// Loop through each possible starting letter for index k,
// the first index for which we have a choice.
for (j=k; j<strlen(str); j++) {
// Place the character stored in index j in location k.
ExchangeCharacters(str, k, j);
// Print out all of the permutations with that character
// just chosen above fixed.
RecursivePermute(str, k+1);
// Put the original character that used to be there back
// in its place.
ExchangeCharacters(str, j, k);
}
}
}
// Pre-condition: str is a valid C String and i and j are valid indexes
// to that string.
// Post-condition: The characters at index i and j will be swapped in
// str.
void ExchangeCharacters(char str[], int i, int j) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}