1. Computing
Send to a Friend via Email

How to shuffle array values

By

Let's say you are building a card game. You have an array of cards, you need to shuffle (mix up the position of cards in the array).

Place a TButton (Button1) and a TListBox (ListBox1) and try:

~~~~~~~~~~~~~~~~~~~~~~~~~
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..54] of Integer;
   i: Shortint;
begin
   Randomize;
   for i := Low(a) to High(a) do a<i> := i;
   Shuffle(a, High(a), SizeOf(Integer)) ;
   ListBox1.Clear;
   for i := 1 to High(a) - 1 do
     ListBox1.Items.Add(IntToStr(a<i>)) ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Delphi: Incompatible type: 'method pointer and regular procedure'
« Delphi tip: Grayscaling a bitmap

©2014 About.com. All rights reserved.