troubleshooting Question

Optimizing a nested loop with recursion

Avatar of wildey100
wildey100 asked on
4 Comments1 Solution239 ViewsLast Modified:

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);
states,i,l,n,j,count,k : integer;
switch : array[0..2] of integer;
  switch[0] := 0;
  switch[1] := 0;
  switch[2] := 0;

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


Thanks in advance. 125 points on offer.

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
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.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros