用于彩票3D的组合算法介绍
用于彩票3D的组合算法介绍
最近想写一个3D彩票的程序,先连抄带改写了一个组合的算法,放在这里,以防丢失,哈哈!
//组合函数,调用例子: Combine('0123456789', memo1.Lines, 4);
procedure Combine(CSet: string; sl: TStrings; Num: Integer);
unit Comb;
interface
uses Classes;
procedure Combine(CSet: string; sl: TStrings; Num: Integer);
implementation
var
n, r: Integer; // n - 字符集数目 r - 取出的数目
c: array[0..10] of Integer;
used: array[0..10] of Integer;
procedure Combine_1(ss: string; sl: TStrings; p, h: Integer);
var
i: Integer;
s: string;
begin
if p = r then begin
s := '';
for i := 0 to r - 1 do s := s + ss[c[i] + 1];
sl.Add(s);
Exit;
end;
for i := h to n - r + p do
if Used[i] = 0 then begin
c[p] := i;
Inc(used[i]);
Combine_1(ss, sl, p + 1, i + 1);
Dec(used[i]);
end;
end;
procedure Combine(CSet: string; sl: TStrings; Num: Integer);
var
i: Integer;
begin
for i := 0 to 10 do used[i] := 0;
n := Length(CSet);
r := Num;
Combine_1(CSet, sl, 0, 0);
end;
end.