unit Unit11; //设定随机数范围, 返回数组长度, 得到一组不重复的随机数 interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm11 = class(TForm) btn1: TButton; procedure btn1Click(Sender: TObject); private //生成的随机数函数 function CreateRandom(const RangeStart, RangeEnd, ResultCount: integer): Tarray<Integer>; { Private declarations } public { Public declarations } end; var Form11: TForm11; implementation {$R *.dfm} //CreateRandom(随机数取值范围起始值, 终止值; 返回数组长度) function TForm11.CreateRandom(const RangeStart, RangeEnd, ResultCount : integer) : Tarray<Integer>; var tmpLst : TStringList; //可以使用泛型列表或数组代替 I, n: Integer; begin if RangeStart >= RangeEnd then raise Exception.Create('错误的随机数范围!'); if ResultCount < 1 then raise Exception.Create('随机数返回数组长度必须大于0!'); tmpLst := TStringList.Create; tmpLst.Capacity := RangeEnd - RangeStart; try for n := RangeStart to RangeEnd do begin tmpLst.Add(IntToStr(n)); end; Randomize; SetLength(Result, ResultCount); for I := 0 to ResultCount do begin n := Random(tmpLst.Count - 1); Result[i] := StrToInt(tmpLst.Strings[n]); tmpLst.Delete(n); end; finally tmpLst.free; end; end; procedure TForm11.btn1Click(Sender: TObject); var MyArr : Tarray<Integer>; I : Integer; s : string; begin s := ''; MyArr := CreateRandom(0, 100, 10); for I := Low(MyArr) to High(MyArr) do s := s + inttostr(Myarr[i]) + ' '; ShowMessage(s); s := ''; MyArr := CreateRandom(100, 1000, 15); for I := Low(MyArr) to High(MyArr) do s := s + inttostr(Myarr[i]) + ' '; ShowMessage(s); end; end.
关键字词: