1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
| unit RandomWords_MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
SpinEdit1: TSpinEdit;
ListBox1: TListBox;
ListBox2: TListBox;
CheckBox1: TCheckBox;
procedure Button1Click(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
type
TWordGenerator = class(TObject)
public
type
TLetter = record
Value: Char;
Count: Integer;
end;
TLetters = array of TLetter;
private
FLetters: TLetters;
FLetterPonderation: Integer;
FPonderation: Boolean;
public
constructor Create(ALetters: string);
function GetWord(ALength: Integer): string;
function GetStat(): TLetters;
property Ponderation: Boolean read FPonderation write FPonderation;
public
class constructor Create();
end;
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
Ls: TWordGenerator.TLetters;
L: TWordGenerator.TLetter;
begin
with TWordGenerator.Create(Edit1.Text) do
try
Ponderation := CheckBox1.Checked;
for I := 0 to SpinEdit1.Value - 1 do
ListBox1.Items.Add(GetWord(10));
Ls := GetStat();
for L in Ls do
ListBox2.Items.Add(Format('%s: %d', [L.Value, L.Count]));
finally
Free();
end;
end;
{ TWordGenerator }
constructor TWordGenerator.Create(ALetters: string);
var
I: Integer;
begin
inherited Create();
SetLength(FLetters, Length(ALetters));
for I := 1 to Length(ALetters) do
FLetters[I-1].Value := ALetters[I];
end;
class constructor TWordGenerator.Create();
begin
Randomize;
end;
function TWordGenerator.GetStat(): TLetters;
begin
Result := FLetters;
end;
function TWordGenerator.GetWord(ALength: Integer): string;
type
PLetter = ^TLetter;
var
I: Integer;
K: Integer;
J, C: Integer;
L: PLetter;
Ls: array of PLetter;
begin
SetLength(Result, ALength);
for I := 1 to ALength do
begin
if FPonderation and (FLetterPonderation > 0) then
begin
for J := Low(FLetters) to High(FLetters) do
begin
L := @FLetters[J];
if L.Count < FLetterPonderation then
begin
C := Length(Ls);
SetLength(Ls, C+1);
Ls[C] := L;
end;
end;
end;
if Length(Ls) > 0 then
begin
K := Random(Length(Ls));
L := Ls[K];
end
else
begin
K := Random(Length(FLetters));
L := @FLetters[K];
end;
Result[I] := L.Value;
Inc(L.Count);
if L.Count > FLetterPonderation then
FLetterPonderation := L.Count;
end;
end;
end. |
Partager