Link to home
Start Free TrialLog in
Avatar of wildey100
wildey100

asked on

Optimizing a nested loop with recursion

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;
           memo1.lines.add(InttoStr(switch[0])+','+InttoStr(switch[1])+','+InttoStr(switch[2]))
        end;
      end;
  end;

end;



Thanks in advance. 125 points on offer.

Richard
ASKER CERTIFIED SOLUTION
Avatar of kretzschmar
kretzschmar
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
just to ask about the b-grade?
Avatar of wildey100
wildey100

ASKER

Sorry, it was my first post and answer grading. Maybe I was being too harsh. Your answer has solved my problem perfectly so I guess I should have marked it as "excellent". Sorry if I have caused offence. I'd be more than happy to regrade it if I could.

Richard.
well,
i could do it (because i'm the page editor)
but it would not be fair against other experts.

so i say let it as it is

for future read

https://www.experts-exchange.com/Programming/Programming_Languages/Delphi/help.jsp#hi73

and btw. welcome to ex-ex :-))

glad to helped you

meikl ;-)