簡體   English   中英

我的堆算法代碼有什么問題?

[英]What's wrong with my Heap's Algorithm code?

我的作業要求我編寫一個程序,該程序從終端(argc 和 argv)獲取一個字符串並打印所有可能的排列。 我曾嘗試使用堆算法,但似乎並沒有奏效。 下面是我的功能。

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

該函數必須返回指向指令指定的字符指針的指針。 這也是為什么有這么多變量的原因(盡管我不確定如何處理字符串的副本。我很確定我需要它)。 測試表明程序會循環,經常循環太多並最終遇到段錯誤。 似乎交換的字符串並沒有使其成為最重要的返回數組。

下面是清理內存分配的代碼返工,它解決了上述注釋中提到的一些問題。 此外,您的算法中有一個錯誤,這條語句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
> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM