我的Heap算法代码出了什么问题?

时间:2016-09-23 03:56:21

标签: c algorithm

我的作业要求我编写一个程序,从终端(argc和argv)获取一个字符串并打印每个可能的排列。我曾尝试使用Heap的算法,但它似乎没有成功。以下是我的功能。

char **getPermutation(char * in)
{
//n is the size of the input string.
 int n = strlen(in);
 int count[n];
 int counter= 0;
 char copy[n];
 char **permutations = malloc(sizeof(char*)*(factorial(n)));
 permutations[0] = in;
 strcpy(in, copy);
 counter++;
 for( int i = 1; i < n;)
 {

  if (count[i] < i){
   if (i%2==0){
    swap(&in[0],&in[i]);
   }
   else
   {
    swap(&in[count[i]],&in[i]);
   }
    permutations[counter] = in;
    strcpy(in, copy);
    counter++;
    count[i]++;
    i = 1;
  }
  else
  {
   count[i] = 0;
   i++;
   }
  }
 return permutations;
 }

该函数必须返回指令指定的字符指针。这也是为什么有这么多变量的原因(虽然,我不确定如何处理字符串的副本。我很确定我需要它)。测试显示程序将循环,经常过多并最终遇到seg故障。看起来好像交换的字符串使其无法进入返回的数组。

1 个答案:

答案 0 :(得分:1)

下面是清理内存分配的代码返工,它解决了上述注释中提到的一些问题。此外,您的算法中存在错误,此语句strcpy(in, copy);使您无法获得所有排列(反而导致重复。)此代码有效但尚未完成,它可以使用更多错误检查和其他完成接触:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

unsigned int factorial(unsigned int n)
{
    /* ... */
}

void swap(char *a, char *b)
{
    /* ... */
}

char **getPermutations(const char *input)
{
    char *string = strdup(input);

    size_t length = strlen(string);

    char **permutations = calloc(factorial(length), sizeof(char *));

    int *counts = calloc(length, sizeof(int)); // point to array of ints all initialized to 0

    int counter = 0;

    permutations[counter++] = strdup(string);

    for (size_t i = 1; i < length;)
    {
        if (counts[i] < i)
        {
            if (i % 2 == 0)
            {
                swap(&string[0], &string[i]);
            }
            else
            {
                swap(&string[counts[i]], &string[i]);
            }
            permutations[counter++] = strdup(string);
            counts[i]++;
            i = 1;
        }
        else
        {
            counts[i++] = 0;
        }
    }

    free(counts);
    free(string);

    return permutations;
 }

int main(int argc, char *argv[])
{

    char *string = argv[1];

    char **permutations = getPermutations(string);

    unsigned int total = factorial(strlen(string));

    for (unsigned int i = 0; i < total; i++)
    {
        printf("%s\n", permutations[i]);
    }

    free(permutations);

    return 0;
}

<强>输出

> ./a.out abc
abc
bac
cab
acb
bca
cba
>