Delphi 面试题 获取5位不重复的数字 数字在 1-8中

function getint(t: Integer): string;
var
  k: array of Byte;
  j, i,: integer;


  function isin(l: integer): Boolean;
  var
    i: Integer;
  begin
    result := False;
    for i := 0 to Length(k) do
    begin
      if l = k[i] then
      begin
        result := true;
        Break;
      end;
    end;
  end;


begin
  if t > 8 then
    Exit;
  case t of
    7:
      begin
        Result := '1234567';
        Exit;
      end;


    8:
      begin
        Result := '12345678';
        Exit;
      end

  end;

   randomize;

  SetLength(k, t);
  i := 0;
  while true do
  begin
    if i >= t then
      Break;
    j := Random(8);
    if (j = 0) or isin(j) then
    begin
      Continue;
    end;
      k[i] := j;
    Inc(i);
  end;
  for i := 0 to t - 1 do
    Result := Result + Format('%d', [k[i]]);
  SetLength(k, 0);

end;

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

加入字母数字生成订单号

function getint(t: Integer): string;
var
  k: array of Byte;
  j, i: integer;
  lchar: string;




  function isin(l: integer): Boolean;
  var
    i: Integer;
  begin
    result := False;
    for i := 0 to Length(k) do
    begin
      if l = k[i] then
      begin
        result := true;
        Break;
      end;
    end;
  end;


begin
  randomize;
  lchar:='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for i:=1 to t do
  Result := Result + lchar[Random(62)+1];
  if t > 8 then
    Exit;
  case t of
    7:
      begin
        Result := Result + '1234567';
        Exit;
      end;


    8:
      begin
        Result := Result +'12345678';
        Exit;
      end
  end;
  SetLength(k, t);
  i := 0;
  while true do
  begin
    if i >= t then
      Break;
    j := Random(8);
    if (j = 0) or isin(j) then
    begin
      Continue;
    end;
    k[i] := j;
    Inc(i);
  end;
  for i := 0 to t - 1 do
    Result := Result + Format('%d', [k[i]]);
  SetLength(k, 0);

end;


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

效率高的还是这个

function getint2(t: integer): string;
var
  i: Integer;
  lchar: string;
  lc: Char;
begin
   lchar:='12345678';
   randomize;
  while true  do
  begin
     if Length(Result) = t then Break;
     lc := lchar[Random(8)+1] ;
     if lc = '' then Continue;
     if Pos(lc,Result) > 0 then Continue;
     Result := Result + lc;
  end;
end;

猜你喜欢

转载自blog.csdn.net/y281252548/article/details/80496970
今日推荐