Search code examples
delphinested-loopsskip

How to skip some nested loops in delphi?


Could anyone please help me in this topic in Delphi?

I have 5 nested "for" block loops iterating with variables k1, k2.. k5.
Another variable k must control the depth of above 5 loops. This variable is defined during run-time.

Is it possible to eliminate the execution of the k inner 'for' blocks as if they had been commented? A short listing of explaining code is here:

k := 2;
for k1 := 1 to 100 do begin  
   for k2 := 1 to 100 do begin  
      for k3 := 1 to 100 do begin  
         for k4 := 1 to 100 do begin {want to skip this loop}
            for k5 := 1 to 100 do begin {want to skip this loop}  
               AnywayDoThat; // must execute anyway  
            end; {k5}  
         end; {k4}  
      end;  
   end;
end;  

Further explaining, as k equals 2, I wish to avoid execution of loops k4 and k5 (lines of code ending in curly brackets), shortening the full flow of the program. Of course, proc AnywayDoThat must execute.

I use Delphi 6.

Edit: Sorry for the bad wording 'eliminated'. The aim was to avoid unnecessary iterations. The trick to skip a loop by making it to execute just once is perfect. Thus, proc AnywayDoThat is reached according to k1, k2, k3 only.


Solution

  • You could use the following trick

    Var 
      Maxes: array [1..5] of integer;
      Eliminators: array [1..5] of integer; // they have to be of same length
    begin
      SetArray(Maxes, [100, 100, 100, 100, 100]);
      SetArray(Eliminators, [1, 1, 1, 1, 1]);
    
      // Here you set K
      K := 2;  // you need to make sure K <= 5 
    
      // Set the Eliminators array 
    
      for I := 1 to K do
        begin
          Eliminators[5-I+1] := Maxes[5-I+1];
        end;
    
      // Now to the loops
    
      for k1 := 1 to Maxes[1] div Eliminators[1] do begin  
        for k2 := 1 to Maxes[2] div Eliminators[2] do begin  
          for k3 := 1 to Maxes[3] div Eliminators[3] do begin  
            for k4 := 1 to Maxes[4] div Eliminators[4] do begin 
              for k5 := 1 to Maxes[5] div Eliminators[5] do begin  
                AnywayDoThat; // must execute anyway  
              end;  
            end;   
          end;  
        end;
      end;  
    
    
    end;
    

    The main idea here is to skip a loop by making it to execute once. This can be further modified to make it skip any loop.