我有两个要洗牌的数组。在下面,您将看到声明和改组示例。
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;
这是我正在使用的过程以及两个数组的声明。
谢谢您的帮助
答案 0 :(得分:0)
您应该使用通用方法来随机排列数组。
我为你写了这个
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;