views:

157

answers:

3

How can I optimize the following code ,

I Need to run 3 sets of loops like this:

for($i=1;$i<=$count-1;$i++){    
  for($j=$i+1;$j<=$count;$j++){
  // do some query use $i and $j

  }
}
for($i=1;$i<=$count-2;$i++){
   for($j=$i+1;$j<=$count-1;$j++){   
     for($k=$j+1;$k<=$count;$k++){
       // do some query use $i and $j and $k
     }
  }
}
for($i=1;$i<=$count-3;$i++){
   for($j=$i+1;$j<=$count-2;$j++){   
      for($k=$j+1;$k<=$count-1;$k++){
     for($l=$k+1;$l<=$count;$l++){ 
       // do some query use $i and $j and $k and $l
       }
     }
  }
}

Is there a way to simplify the code, perhaps to connect the loops together ?

thanks !

+1  A: 

The big problem is that the inner loops are run multiple times. You can get around this by checking i === 1 and j === 2 inside the loops and only running the appropriate code if true.

Ignacio Vazquez-Abrams
I did not understand how to implement it, I'd be grateful if you could specify
Haim Evgi
A: 

Micro-optimization: Use

++$i

rather than

$i++

and equivalent for $j++, $k++ and $l++

But what are you doing in these loops: it's entirely possible that your do some query (database?) could be changed to remove the loops completely... and that would be far more effective than any micro-optimisations

Mark Baker
This is just **pathetic**. Sorry, but how is this the accepted answer?
strager
+1  A: 

This should do it (untested):

for($i = 1; $i <= $count - 3; $i++) {
    for($j = $i + 1; $j <= $count; $j++) {
        // i,j query

        if($j > $count - 2) {
            continue;
        }

        for($k = $j + 1; $k <= $count; $k++) {
            // i,j,k query

            if($k > $count - 1) {
                continue;
            }

            for($l = $k + 1; $l <= $count; $l++) {
                // i,j,k,l query
            }
        }
    }
}

Note that the queries are no longer in their original order.

As it has been said, there's no way to optimize this further without knowing the queries you are running.

strager