【问题标题】:How to count the total possibilities of permute? (in C)如何计算置换的总可能性? (在 C 中)
【发布时间】:2021-07-20 06:38:39
【问题描述】:

我是编程新手,我正在尝试在 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;
}

【问题讨论】:

  • if( scanf("%20s", str) == 1 ) { ...
  • 每次if (i == n) 为真时增加一个“计数器”?
  • len 变量字符串中的字符数。所以你不需要第二个main 中的任何代码。如果您想查看长度,只需printf("%d\n", len);
  • 谢谢各位。它现在正在工作!我遵循@user3386109 的提示。现在我还有一个问题,我会编辑帖子

标签: c count permute


【解决方案1】:

您可以在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;
}

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    相关资源
    最近更新 更多