Permutations with Delphi

About Delphi Programming.
Tips, tricks, questions, projects

Moderator: Admin

Permutations with Delphi

Postby Tee » Mon May 01, 2006 3:49 pm

A simple algorithm to make permutations with Delphi:
Code: Select all
Type
  TForm1 = Class (TForm)
    LB1: TListBox;
    Memo1: TMemo;
    Button1: TButton;
    Procedure Button1Click (Sender: TObject);
  Private
    { Private declarations }
  Public
    { Public declarations }
    Procedure Swap (var V: Array Of Integer; I, J: Integer);
    Procedure Perm (Var V: Array Of Integer; n, I: Integer);
  End;

Var
  Form1                          : TForm1;
  V                              : Array Of Integer;


Implementation

{$R *.dfm}

Procedure TForm1.Swap (var V: Array Of Integer; I, J: Integer);
Var
  T                              : Integer;
Begin
  T:= V [I];
  V [I]:= V [J];
  V [J]:= T;
End;


Procedure TForm1.Perm (Var V: Array Of Integer; n, I: Integer);
Var
  J                              : Integer;
  S                              : String;
Begin
  If I = n Then
    Begin
      S:= '';
      For J:= 0 To n -1 Do
        Begin
          S:= S + ' '+ IntToStr (V [J]);
        End;
      LB1.Items.Add (S);
    End
  Else
    For J:= I To n - 1 Do
      Begin
        Swap (V, I, J);
        Perm (V, n, I + 1);
        Swap (V, I, J);
      End;
End;



Procedure TForm1.Button1Click (Sender: TObject);
Var
  L, I                           : Integer;
Begin
  L:= Memo1.Lines.Count;
  SetLength (V, L);

  For I:= 0 To Memo1.Lines.Count - 1 Do
    V [I]:= StrToInt (Memo1.Lines [I]);
  Perm (V, L, 0);
End;
User avatar
Tee
VIP User (Very Important Person)
 
Posts: 20
Joined: Fri Apr 14, 2006 3:16 pm

Return to Delphi

Who is online

Users browsing this forum: No registered users and 1 guest

cron