Delphi洗牌算法 - 将一个数组随机乱序

用于考试时乱序,相同的试题,但每位考生看到的题序不同。

Delphi洗牌算法 - 将一个数组随机乱序_第1张图片


unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Grids;

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure InitValue();
    procedure tmprandom();
  end;

var
  Form1: TForm1;
  Array20 : array[1..20] of String;

implementation

{$R *.dfm}

//布局
procedure TForm1.FormCreate(Sender: TObject);
begin
  Self.Width := 950;
  Self.Height:= 270;
  //固定行列
  StringGrid1.FixedCols := 1 ;
  StringGrid1.FixedRows := 1;
  //表格数
  StringGrid1.RowCount := 5+1;
  StringGrid1.ColCount := 20+1; 
  //列宽
  StringGrid1.DefaultColWidth := 40;
  StringGrid1.DefaultRowHeight := 20;
end;

//初始化数组
procedure TForm1.InitValue();
var
  i : integer;
begin
  for i:=1 to 20 do
  begin
    Array20[i] := inttostr(i);
  end;
end;

//随机得到新数组
procedure TForm1.tmprandom();
var
  i,j : integer;
  swp:string;
begin
  randomize;
  for i:=1 to 20 do
  begin
  j := 1 + random(20);
  swp := Array20[i];
  Array20[i] := Array20[j];
  Array20[j] := swp;
  end;
end;

//显示原有数组
procedure TForm1.Button1Click(Sender: TObject);
var
  i : integer;
begin
  InitValue;
  for i:=1 to 20 do
  begin
    StringGrid1.Cells[i,1]:= Array20[i];
  end;
end;

//显示新数组
procedure TForm1.Button2Click(Sender: TObject);
var
  i : integer;
begin
  tmprandom;
  for i:=1 to 20 do
  begin
    StringGrid1.Cells[i,2]:= Array20[i];
  end;
end;

end.


你可能感兴趣的:(DELPHI,洗牌算法)