Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert function from recursion to iteration

I have this function that I wrote that is abysmally slow since php does not handle recursion well. I am trying to convert it to a while loop, but am having trouble wrapping my head around how to do it.

Can anyone give me some tips?

    public function findRoute($curLoc, $distanceSoFar, $expectedValue) {

    $this->locationsVisited[$curLoc] = true;
    $expectedValue += $this->locationsArray[$curLoc]*$distanceSoFar;

    $at_end = true;
    for($i = 1; $i < $this->numLocations; $i++) {
        if($this->locationsVisited[$i] == false) {
            $at_end = false;

            if($expectedValue < $this->bestEV)
                $this->findRoute($i, $distanceSoFar + $this->distanceArray[$curLoc][$i], $expectedValue);
        }
    }

    $this->locationsVisited[$curLoc] = false;

    if($at_end) {
        if($expectedValue < $this->bestEV) {
            $this->bestEV = $expectedValue;
        }
    }
}
like image 226
Eric Conner Avatar asked Sep 10 '26 04:09

Eric Conner


1 Answers

I'm not going to convert your code, but you can convert a recusive function into an iterative one by creating a stack:

$stack= array();

And instead of invoking $this->findroute(), push your parameters onto this stack:

$stack[] = array($i, $distanceSoFar + $this->distanceArray[$curLoc][$i], $expectedValue);

Now surround basically everything in your function into a while loop draining the stack after having primed it:

while ($stack) { 
    // Do stuff you already do in your function here
like image 161
Kristopher Ives Avatar answered Sep 12 '26 18:09

Kristopher Ives



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!