我有两个数组要混洗。下面您将看到声明和shuffle的示例。
var
highNums : array[1..9] of integer;
lowNums : array[1..20] of integer;
begin
Q := 0;
for I := 1 to Length(highNums) do
begin
highNums[I] := q;
end;
for K := 1 to Length(lowNums) do
begin
lowNums[K] := q;
end;
bigNums[] {25 ..225} every 25
lowNumes[] {1..10} two of each number
procedure shuffleHighArray();
var
I, ToSwapHigh, HighTemp : integer;
begin
for I := 1 to length(highNums) do
begin
toSwapHigh := Random(length(highNums));
HighTemp := highNums[I];
highNums[I] := highNums[toSwapHigh];
highNums[toSwapHigh] := HighTemp;
end;
end;
procedure shuffleLowArray();
var
K, ToSwapLow, LowTemp : integer;
begin
for K := 1 to length(lowNums) do
begin
toSwapLow := random(length(lowNums));
LowTemp := lowNums[K];
lowNums[K] := lowNums[toSwapLow];
lowNums[toSwapLow] := LowTemp;
end;
end;
以下是我正在使用的过程以及这两个数组的声明
感谢您的帮助
您应该使用一个通用方法来打乱数组。
我为你写了这个:
uses
System.Math;
type
TArrayHelper = class abstract
public
class constructor Create;
class procedure PermuteArray<T>(var A: array of T);
end;
{ TArrayHelper }
class constructor TArrayHelper.Create;
begin
Randomize;
end;
class procedure TArrayHelper.PermuteArray<T>(var A: array of T);
var
Tmp: T;
i, j: Integer;
begin
for i := High(A) downto low(A) do
begin
j := RandomRange(0, i);
Tmp := A[i];
A[i] := A[j];
A[j] := Tmp;
end;
end;
如果你想测试它。在表格上放一个按钮和一个备忘录,然后试试这个代码:
procedure TForm1.Button1Click(Sender: TObject);
procedure DisplayArray(A: array of Integer);
var
i: Integer;
s: String;
begin
s := '[';
for i := low(A) to min(10, High(A)) do
s := s + A[i].ToString + ',';
s[Length(s)] := ']';
Memo1.Lines.Add(s);
end;
var
i: Integer;
Nums: array [1 .. 9000] of Integer;
begin
Memo1.Lines.Clear;
for i := low(Nums) to High(Nums) do
Nums[i] := i;
DisplayArray(Nums);
TArrayHelper.PermuteArray(Nums);
DisplayArray(Nums);
end;