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

delphi5年前 (2020)发布 admin
856 0

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

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

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Grids;

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    btn1: TBitBtn;
    btn2: TBitBtn;
    procedure FormCreate(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }


  end;

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

implementation

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

//随机得到新数组
procedure 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.btn1Click(Sender: TObject);
var
  i : integer;
begin
  InitValue;
  for i:=1 to 20 do
  begin
    StringGrid1.Cells[i,1]:= Array20[i];
  end;

end;

procedure TForm1.btn2Click(Sender: TObject);
var
  i : integer;
begin
  tmprandom;
  for i:=1 to 20 do
  begin
    StringGrid1.Cells[i,2]:= Array20[i];
  end;
end;

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;

end.

© 版权声明

相关文章