2

我的代码有问题。我最初是在 Lazarus 中编写的,但是在 Windows 和 Linux 上的 fpc 编译器上编译它仍然给我带来了问题。Linux 给出“分段错误”和 windows 外部 SIGSEV。

我的目标是用这个程序生成排列。这只是为了好奇和学习。

节目来源:

program CombinationGeneration;


{$mode objfpc}{$H+}

const
     K              = 6;    // Number of elements chosen
     N              = 26;   // Number of elements to choose from
     ALPHABET: Array[1..N] of Char = ('A','B','C','D','E','F','G','H','I','J','K','L','M',          // Elements 
                                      'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');         //

Type
   TCombination = Array of Byte;        // Combination elemnts array type
   PCombination = ^TCombination;        // Pointer to combination elements array



{ Rotate
  Rotate digits forward in alphabet.
  If last item in alphabet is reached, then rotate element before current in combination. }
procedure Rotate( const Combination:PCombination; Element:integer );
begin

     { Check if rotation is completed }
         if Combination^[Element] = High(ALPHABET) then
     begin
                { If rotation is completed:
                    * rewind element to first in ALPHABET Low()
                    * Check if the the element before current exists, then rotate it. }
                Combination^[Element] := Low(ALPHABET);

                if Element > Low(Combination^) then
                     Rotate( Combination, Element-1 )
        else
                    Writeln('The end. ');
         end else
         { Rotation is not complete and just rotate forward the current element. }
     begin
                inc(Combination^[Element]);
        {:: Write out combination HERE!!! ::}

        { If it is not the last element in combination,
            we must rotate the others after it. So go back to High().  }
        if Element < High(Combination^) then
                     Rotate( Combination, High(Combination^) )
        else
            Rotate( Combination, Element );
     end;
end;



var
   Comb     : TCombination;                         // Holds the current combination
     i          : integer;                          // Iterator for various stuff

begin
    { Set the first combination, length is K }
    SetLength(Comb,K);

  { Fill with initial values }
  for i:=Low(Comb) to High(Comb) do
  begin
         Comb[i]:=Low(ALPHABET);                    // Probably [0,0,0]
    end;

  { Calculate permutations  }
    rotate(@Comb, High(Comb));
  readln;
end.

它可以执行大约 694 000 次“旋转”功能调用,然后它就崩溃了。它曾经做大约 59 000,但我通过引用传递了组合数组,后来我通过指针传递了它。(上一版没有改进,或者你能告诉我吗?)

If I decrease the N and K values until the max permutations value becomes smaller
than this 694 000, then it runs perfect. No errors. 

For example let's say we have 14 elemnts in alphabet and k = 5. 
The formula is 14^5 = 537 824 . And it is generated flawlessly. 
Also full alphabet(26) and 4 chosen works fine -  26^4=456 976 

调用堆栈的一些输出(复制文本使 Lazarus 崩溃):

在此处输入图像描述

所以..你能发现任何错误......内存泄漏,浪费......?

拉兹版 1.0.8 Fpc 版本。2.6.2

谢谢!

4

0 回答 0