Search code examples
javaloopsnested-loops

Dynamic nested loops with dynamic bounds


I have a LinkedList< Point > points ,with random values:

10,20
15,30
13,43
  .
  .

I want to perform this kind of loop:

for (int i= points.get(0).x; i< points.get(0).y; i++){
   for (int j= points.get(1).x; j< points.get(1).y; j++){
     for (int k= points.get(2).x; k< points.get(2).y; k++){
                         ...
                         ...
     }
   }
}

How can I do that if I don't know the size of the list?


Solution

  • There's probably a better way to solve equations like that with less cpu and memory consumption but a brute-force approach like your's could be implemented via recursion or some helper structure to keep track of the state.

    With recursion you could do it like this:

     void permutate( List<Point> points, int pointIndex, int[] values ) {
       Point p = points.get(pointIndex);
       for( int x = p.x; x < p.y; x++ ) {
         values[pointIndex] = x;
    
         //this assumes pointIndex to be between 0 and points.size() - 1
         if( pointIndex < points.size() - 1 ) {          
           permutate( points, pointIndex + 1; values );
         }
         else { //pointIndex is assumed to be equal to points.size() - 1 here
           //you have collected all intermediate values so solve the equation
           //this is simplified since you'd probably want to collect all values where the result is correct
           //as well as pass the equation somehow
           int result = solveEquation( values );
         }
       }
     }
    
     //initial call
     List<Point> points = ...;
     int[] values = new int[points.size()];
     permutate( points, 0, values );
    

    This would first iterate over the points list using recursive calls and advancing the point index by one until you reach the end of the list. Each recursive call would iterate over the point values and add the current one to an array at the respective position. This array is then used to calculate the equation result.

    Note that this might result in a stack overflow for huge equations (the meaning of "huge" depends on the environment but is normally at several 1000 points). Performance might be really low if you check all permutations in any non-trivial case.