I'm new to programming, and i'm trying to complement this code in C to permute strings, currently it shows all the words exchanged and counts how many characters the word has.
But I would like it to count the number of lines generated by the permutation too, and in this part, the code is not working. I do not know what else to do!
Example: The word "hi", generates two lines: hi, and ih. (In this case, i want the program write "generated words: 2")
the code:
#include <string.h>
#include <stdio.h>
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a + i), (a + j)); //backtrack
}
}
}
int main()
{
char str[21];
int len;
int cont = 1;
int fatorial = 1;
printf("\nType a word: ");
scanf("%s", str);
len = strlen(str);
permute(str, 0, len - 1);
printf("\nNumber of letters: %d\n", len);
while (cont < len)
{
fatorial = fatorial * cont;
cont++;
}
printf("\nPossibilities:%d", fatorial);
return 0;
}
You could increment a counter in
permute
. Something like: