具有动态边界的动态嵌套循环

Dynamic nested loops with dynamic bounds

我有一个 LinkedList< Point > points ,具有随机值:

10,20
15,30
13,43
  .
  .

我想执行这种循环:

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++){
                         ...
                         ...
     }
   }
}

如果我不知道列表的大小,我该怎么做?

可能有更好的方法来解决像这样的方程式,减少 cpu 和内存消耗,但是像你这样的 brute-force 方法可以通过递归或一些辅助结构来跟踪状态.

通过递归,你可以这样做:

 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 );

这将首先使用递归调用迭代点列表并将点索引推进一个,直到到达列表的末尾。每个递归调用都会遍历点值并将当前值添加到相应位置的数组中。然后使用此数组计算等式结果。

请注意,这可能会导致 巨大的 方程式的堆栈溢出("huge" 的含义取决于环境,但通常为数 1000 个点)。如果您检查任何 non-trivial 情况下的所有排列,性能可能 真的 低。