troubleshooting Question

# Optimizing a nested loop with recursion

Delphi
Hi,

I have the following code below that iterates all the possible combinations of a three state switch for three swithes. Using recursion I know this is possible to work with N number of switches but can't work out how to do it.
The code should loop though and give you 3^n combinations, if you can do this - using recursion or not, i don't mind - recursion was just the way I tried.

procedure TForm1.Button1Click(Sender: TObject);
Var
states,i,l,n,j,count,k : integer;
switch : array[0..2] of integer;
begin
switch[0] := 0;
switch[1] := 0;
switch[2] := 0;

For k := -1 to 1 do
begin
switch[2] := k;
For l := -1 to 1 do
begin
switch[1] := l;
For i := -1 to 1 do
Begin
switch[0] := i;
end;
end;
end;

end;

Thanks in advance. 125 points on offer.

Richard
Join the community to see this answer!
###### Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.