16,748
社区成员
发帖
与我相关
我的任务
分享
nit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TComputingData = record//存放数据
ID : string;//id编号
v : integer;//值
select : boolean;//是否被组合了
end;
TUpshotData = record//存放结果
ID:string;
v:string;
end;
var tmp:array[0..49]of TComputingData;//存放数据
procedure TForm1.Button1Click(Sender: TObject);
var i,len:integer;
upshot:array of TUpshotData;//存放结果
bID,bV:string;
function GetMatch(var idstr,vstr:string; v,index:integer):boolean;
var j:integer;
aID,aV:string;
begin
Result := false;//先假定没匹配
for j:=index to 49 do begin
if tmp[j].select then continue;
if v+tmp[j].v = 50 then begin //匹配上了
tmp[j].select:=true;
idstr:=idstr+','+Format('%.2d',[j]);
vstr:=vstr+','+inttostr(tmp[j].v);
Result := true;
exit;//不再找
end;
end;
//未匹配:
for j:=index to 49 do begin //将上一个数与当前数(和少于50)继续匹配下一个数
if tmp[j].select then continue;
if v+tmp[j].v>50 then continue;
aID:=idstr+','+Format('%.2d',[j]);
aV:=vstr+','+inttostr(tmp[j].v);
tmp[j].select:=true;
if GetMatch(aID,aV,v+tmp[j].v,j+1) then begin//匹配上了
idstr:=aID;
vstr:=aV;
Result := true;
break;//不再找
end
else
tmp[j].select:=false;
end;
end;
begin
memo1.Text:='';
randomize;
for i:=0 to 49 do begin
tmp[i].ID:=Format('%.2d',[i]);
tmp[i].v:=random(49)+1;
tmp[i].select:=false;
end;
memo1.Lines.Append('待处理数据:');
for i:=0 to 49 do
memo1.Lines.Append(Format('%.2d',[i])+'----'+inttostr(tmp[i].v));
len:=-1;
for i:=0 to 48 do begin
if tmp[i].select then continue;
bID:=Format('%.2d',[i]);
bV:=inttostr(tmp[i].v);
tmp[i].select:=true;
if GetMatch(bID,bV,tmp[i].v,i+1) then begin
inc(len);
setlength(upshot,len+1);
upshot[len].ID:=bID;
upshot[len].v:=bV;
end
else
tmp[i].select:=false;
end;
if len<0 then
memo1.Lines.Append('没有能组合为50的结果。')
else begin
memo1.Lines.Append('找到的组合结果是:');
for i:=0 to len do
memo1.Lines.Append('ID号:'+upshot[i].ID+'---对应的值:'+upshot[i].v);
end;
end;
end.