How to count the total possibilities of permute? (in C)

143 Views Asked by At

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;
}
1

There are 1 best solutions below

0
On

You could increment a counter in permute. Something like:

#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 *count)
{
        int j;
        if( i == n ){
                printf("%s\n", a);
                *count += 1;
        } else {
                for( j = i; j <= n; j += 1 ){
                        swap(a + i, a + j);
                        permute(a, i + 1, n, count);
                        swap((a + i), (a + j));
                }
        }
}

int
main(int argc, char **argv)
{
        char buf[1024];
        char *str = argc > 1 ? argv[1] : buf;
        int len;
        int contador = 0;

        if( argc < 2 ){
                printf("\nType a word: ");
                scanf("%1023s", buf);
        }
        len = strlen(str);
        permute(str, 0, len - 1, &contador);
        printf("\nNumber of words: %d\n", contador);

        return 0;
}