0

我是编程新手,我正在尝试在 C 中补充此代码以置换字符串,目前它显示所有交换的单词并计算该单词有多少个字符。

但我也希望它计算排列生成的行数,在这部分,代码不起作用。我不知道还能做什么!

示例:单词“hi”生成两行:hi 和 ih。(在这种情况下,我希望程序写“生成的单词:2”)

编码:

#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;
}
4

1 回答 1

0

您可以在permute. 就像是:

#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;
}
于 2021-04-27T02:42:17.217 回答