Beranda > Delphi > How to randomize without getting duplicate values

How to randomize without getting duplicate values

procedure Shuffle(var aArray; aItemCount: Integer; aItemSize: Integer);
var
Inx: Integer;
RandInx: Integer;
SwapItem: PByteArray;
A: TByteArray absolute aArray;

begin
if (aItemCount > 1) then
begin
GetMem(SwapItem, aItemSize);
try
for Inx := 0 to (aItemCount - 2) do
begin
RandInx := Random(aItemCount - Inx);
Move(A[Inx * aItemSize], SwapItem^, aItemSize);
Move(A[RandInx * aItemSize],
A[Inx * aItemSize], aItemSize);
Move(SwapItem^, A[RandInx * aItemSize],
aItemSize);
end;
finally
FreeMem(SwapItem, aItemSize);
end;
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
a: array[1..10] of Integer;
i: Shortint;
begin
Randomize;
for i := Low(a) to High(a) do a[i] := i;
Shuffle(a, High(a), SizeOf(Integer));
for i := 1 to High(a) - 1 do
ListBox1.Items.Add(IntToStr(a[i]));
end;

Iklan
Kategori:Delphi
  1. Belum ada komentar.
  1. No trackbacks yet.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: