(急)请教P(m,n)排列的问题? (50分)

B

baidh

Unregistered / Unconfirmed
GUEST, unregistred user!
请问:
如何编写出在m个数中取n个数的排列?
比如:P(8,4),P(6,4)?
请给出详细源程序。
 
转贴
var
cc: array [0..30] of byte;
flag : array [1..30] of 0..1;
M,N : integer;
procedure com(step:integer);
var
i,j : byte;
begin
if (step<=M) then

begin
for i:=1 to Ndo
if ((flag)=0) and (i>cc[step-1]) then

begin
flag:=1;
cc[step] := i;
com(step+1);
flag := 0;

end;
end
else
begin
for j:=1 to Mdo
write(cc[j],' ');

writeln;
end;
end;

begin
fillchar(flag,sizeof(flag),0);
N := 3;
M := 3;
cc[0] := 0;cc[1]:=1;
com(1);
readln;
// Insert user code here
end.
 
怎么没有答呀?
to:mlzhou
write(cc[j],' ');
执行时出错,怎么回事?
 
怎么没人关注,我再加150分,回答后奉上!!!
 
注:TBuffer类见 http://www.delphibbs.com/delphibbs/dispq.asp?lid=968511
function PNMNum(N,M:Integer):Double;
var
i:Integer;
begin
Result:=1;
for i:=N-M+1 to Ndo
Result:=Result*i;
end;
function PNM(const N,M:Integer;out Count:Integer):String;
var
A:array of Integer;
i:Integer;
Buf:TBuffer;
StartTime:DWord;
TotalCount:Double;
procedure Gen(Level:Integer);
var
j,mm:Integer;
mstr:String;
begin
if Level=M then
begin
mstr:='';
for j:=0 to M-1do
mstr:=mstr+IntToStr(A[j])+#9;
mstr:=mstr+#13#10;
Buf.WriteBuf(@mstr[1],Length(mstr));
Inc(Count);
if Count mod 1000=0 then
begin
Form1.Caption:=Format('%.3f%% %.7d Time: %.2fs Buffer Size: %.2fM',
[100*Count/TotalCount,Count,(GetTickCount-StartTime)/1000,
Buf.ContentSize/(1024*1024)]);
Application.ProcessMessages;
end;
exit;
end;
mm:=A[Level];
for j:=Level to N-1do
begin
A[Level]:=A[j];
A[j]:=mm;
Gen(Level+1);
A[j]:=A[Level];
A[Level]:=mm;
end;
end;
begin
Result:='';
Count:=0;
if (N<1) or (M>N) or (M<1) then
exit;
Buf:=TBuffer.Create(0,4*1024*1024);
SetLength(A,N);
TotalCount:=PNMNum(N,M);
StartTime:=GetTickCount;
for i:=0 to N-1do
A:=i;
Gen(0);
Result:=Buf.AsString;
Buf.Free;
end;

>>write(cc[j],' ');
执行时出错
那是DOS输出,你新建一个Console App就可以用了。
 
program CMN;
{$APPTYPE CONSOLE}
uses
SysUtils;
const
MaxI = 50;
var
M, N: integer;
Count: integer;
R: array[1..MaxI] of byte;
procedure Print;
var
i: integer;
begin
for i:=1 to Ndo
Write(R, ' ');
Writeln;
end;

procedure Search(d: integer);
var
i, j: integer;
dup: boolean;
begin
if d>N then
begin
Print;
Inc(Count);
Exit;
end;
for i:=1 to Mdo
begin
dup := false;
for j:=1 to d-1do
if R[j]=i then
begin
dup := true;
break;
end;
if dup then
Continue;
R[d] := i;
Search(d+1);
R[d] := 0;
end;
end;

begin
{ TODO -oUser -cConsole Main : Insert code here }
Write('Input Your M and N here:');
Readln(M, N);
FillChar(R, SizeOf(R), 0);
Count := 0;
Search(1);
Writeln('The Total Count is:', Count);
Writeln('Press AnyKey To end.
..');
Readln;
end.
 
upfeed:
你给出的算法正确,但是结果都输出的屏幕上去了,怎样能把结合存为一个文件(例如:文本文件)。
 
有两个方法:
一、修改源程序,把所有的write的函数都加入一个参数(麻烦)
二、在命令行(DOS)下运行程序,但是要加参数,如:
cmn > 1.txt
则会输入到1.txt
 
upfeed:
我新开了一个问题,请进来拿分。
 
多人接受答案了。
 
顶部