svět, kde se rodí nová budoucnost   
 
Delphi headDelphi Tips

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;

//Simon J Stuart, Project: Equilibrium
 

Back to Index of Tips

 

 

Send mail to radek.novak@infojet.cz with questions or comments about this web site.
Copyright © 1999-2002 Infojet.cz
Last modified: 26.07.2002