Procedure GetRandom(nEnd:Integer);
var
  nTmp,nTmp2:Integer; LstTmp:TStringList;
begin
  LstTmp:=TStringList.Create;
  for nTmp:=0 to nEnd-1 do LstTmp.Add(IntToStr(nTmp));
  for nTmp:=nEnd-1 Downto 0 do
  begin
    Randomize; nTmp2:=Random(nTmp+1);
    ShowMessage(LstTmp[nTmp2]);//显示获取的随机数
    LstTmp.Delete(nTmp2);
  end;
  LstTmp.Free;
end;

解决方案 »

  1.   

    1. randomize只应该在程序启动时调用一次, 不应该在循环里不停调用
    2. 取得一个整数随机数, 搞那么多字符串处理不累吗? 你的代码包含大量申请内存和释放内存的操作, 这些操作是很慢的.算法思路是对的, 换成对整数数组的操作就完美了
      

  2.   

    Procedure GetRandom(nEnd:Integer);
    var
      nTmp,nTmp2 : Integer;
      LstTmp : array of Integer;   //用整数数组代替TStringList提升速度
    begin
      Randomize;     //Randomize只需要调用一次
      SetLength(LstTmp,nEnd);   //只需要分配一次内存, 而每次调用用TStringList.Add都会导致内存分配
      for nTmp := 0 to nEnd-1 do LstTmp[nTmp] := nTmp;  //直接对数组下标操作不涉及内存分配
      for nTmp := nEnd-1 downto 0 do
      begin
        nTmp2 := Random(nTmp+1);
        ShowMessage(inttostr(LstTmp[nTmp2]));
        LstTmp[nTmp2] := LstTmp[nTmp];   //这样可以避免内存释放操作
      end;
    end;  //LstTmp在函数调用完成后自动释放