主题:[讨论]实现一个全排列算法 总是运行不过去 高手请指教
这个算法我是抄别人的 用vb写的 我改成了Delphi 主要就是通过按钮点击 把结果显示在memo中 但是总是进入死循环 百思不得其解 请高手指教 下面我附上 vb源码 和我改的Delphi
vb源码:
DECLARE SUB QQ (x)
DIM SHARED m, n AS INTEGER
DIM SHARED a(1 TO 100) AS INTEGER '所有数组的长度,>M即可
DIM SHARED c(1 TO 100) AS INTEGER
DIM SHARED b(1 TO 100) AS STRING
DIM SHARED q$
CLEAR : CLS
m = 5: n = 2 'm、n、q$ 根据实际要求进行改变
q$ = "ASDFGH"
x = n
CALL QQ(x)
END
SUB QQ (x)
c(x) = 1
DO
IF (a(c(x)) = 1) THEN GOTO continue
a(c(x)) = 1
b(x) = MID$(q$, c(x), 1)
IF x > 1 THEN
CALL QQ(x - 1)
ELSEIF x = 1 THEN
FOR j = n TO 1 STEP -1
PRINT b(j);
NEXT j
PRINT " ";
END IF
a(c(x)) = 0
continue:
c(x) = c(x) + 1
LOOP WHILE c(x) <= m
END SUB
这是Delphi:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
a,c:array[1..100]of integer;
b:array[1..100]of char;
q:string;
m,n,j:integer;
procedure qq(x:integer);
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
m:=5;
n:=2;
q:='abcde';
qq(2);
end;
procedure qq(x:integer);
begin
c[x]:=1;
while c[x]<=m do
begin
if (a[c[x]]=1) then c[x]:=c[x]+1 ;
a[c[x]]:=1;
b[x]:=q[x];
if x>1 then
qq(x-1)
else if x=1 then
begin
for j:=n downto 1 do
form1.Memo1.Text:=form1.Memo1.Text+b[j];
form1.Memo1.Text:=form1.Memo1.Text+'';
end;
a[c[x]]:=0;
end;
end;
end.
vb源码:
DECLARE SUB QQ (x)
DIM SHARED m, n AS INTEGER
DIM SHARED a(1 TO 100) AS INTEGER '所有数组的长度,>M即可
DIM SHARED c(1 TO 100) AS INTEGER
DIM SHARED b(1 TO 100) AS STRING
DIM SHARED q$
CLEAR : CLS
m = 5: n = 2 'm、n、q$ 根据实际要求进行改变
q$ = "ASDFGH"
x = n
CALL QQ(x)
END
SUB QQ (x)
c(x) = 1
DO
IF (a(c(x)) = 1) THEN GOTO continue
a(c(x)) = 1
b(x) = MID$(q$, c(x), 1)
IF x > 1 THEN
CALL QQ(x - 1)
ELSEIF x = 1 THEN
FOR j = n TO 1 STEP -1
PRINT b(j);
NEXT j
PRINT " ";
END IF
a(c(x)) = 0
continue:
c(x) = c(x) + 1
LOOP WHILE c(x) <= m
END SUB
这是Delphi:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
a,c:array[1..100]of integer;
b:array[1..100]of char;
q:string;
m,n,j:integer;
procedure qq(x:integer);
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
m:=5;
n:=2;
q:='abcde';
qq(2);
end;
procedure qq(x:integer);
begin
c[x]:=1;
while c[x]<=m do
begin
if (a[c[x]]=1) then c[x]:=c[x]+1 ;
a[c[x]]:=1;
b[x]:=q[x];
if x>1 then
qq(x-1)
else if x=1 then
begin
for j:=n downto 1 do
form1.Memo1.Text:=form1.Memo1.Text+b[j];
form1.Memo1.Text:=form1.Memo1.Text+'';
end;
a[c[x]]:=0;
end;
end;
end.