rando
rando

Reputation: 377

how to turn a recursive algorithms into an iterative one

I have this algorithm I wrote but I do not really know if it is possible to convert it to iterative one. I am trying to get the adjacency nodes for every node in cube-like shape. The adjacent nodes must satisfy two conditions:

  1. It is a gray node.
  2. It is within a radius of distance

def find_continumm(seed, node, row, gray, xyz, distance):
"""
seed: the nodes we want to find the adjacent nodes for. 
node: the candidate nodes to be in the adjacency.
row:  save the nodes that are adjacent. 
gray: boolean array that tells if a node is a gray or not. 
xyz: the 3 dim of the shape. 
distance: the radius
"""
    node_ravel = np.ravel_multi_index(node, xyz)
    if node_ravel in row or ~gray[node_ravel] or math.dist(node, seed) > distance:
        return
    row.add(node_ravel)
    if node[0] < xyz[0]:
        node[0] = node[0] + 1
        find_continumm(seed, node, row, gray, xyz, distance)
        node[0] = node[0] - 1
    if node[0] > 0:
        node[0] = node[0] - 1
        find_continumm(seed, node, row, gray, xyz, distance)
        node[0] = node[0] + 1
    if node[1] < xyz[1]:
        node[1] = node[1] + 1
        find_continumm(seed, node, row, gray, xyz, distance)
        node[1] = node[1] - 1
    if node[1] > 0:
        node[1] = node[1] - 1
        find_continumm(seed, node, row, gray, xyz, distance)
        node[1] = node[1] + 1
    if node[2] < xyz[2]:
        node[2] = node[2] + 1
        find_continumm(seed, node, row, gray, xyz, distance)
        node[2] = node[2] - 1
    if node[2] > 0:
        node[2] = node[2] - 1
        find_continumm(seed, node, row, gray, xyz, distance)
        node[2] = node[2] + 1

Upvotes: 1

Views: 175

Answers (1)

Mark Saving
Mark Saving

Reputation: 1787

Yes, it is always possible to turn a recursive algorithm into an iterative algorithm. The general procedure for doing this is switching to continuation passing style, applying defunctionalization, and then applying tail-call elimination. The composition of these three transformations will turn a recursive function into an iterative function, possibly requiring a stack.

Before I apply this to your code, I will briefly rewrite your code as follows:

def find_continumm(seed, node, row, gray, xyz, distance):
    def helper():
        node_ravel = np.ravel_multi_index(node, xyz)
        if node_ravel in row or ~gray[node_ravel] or math.dist(node, seed) > distance:
            return
        row.add(node_ravel)
        for i in range(3):
            if node[i] < xyz[i]:
                node[i] += 1
                helper()
                node[i] -= 1
            if node[i] > 0:
                node[i] -= 1
                helper()
                node[i] += 1
    helper()

You can see for yourself that this is equivalent to your version of the code. I will do one final re-write to use a while-loop instead of a for-loop:

def find_continumm(seed, node, row, gray, xyz, distance):
    def helper():
        node_ravel = np.ravel_multi_index(node, xyz)
        if node_ravel in row or ~gray[node_ravel] or math.dist(node, seed) > distance:
            return
        row.add(node_ravel)
        i = 0
        while i < 3:
            if node[i] < xyz[i]:
                node[i] += 1
                helper()
                node[i] -= 1
            if node[i] > 0:
                node[i] -= 1
                helper()
                node[i] += 1
            i += 1
    helper()

This dramatically simplifies the code and makes turning it into an iterative version much simpler.

The resulting iterative version is:

beginning = 0
entering_loop = 1
finishing_first_call = 2
enter_second_if = 3
finishing_second_call = 4
increment_i = 5
# the actual values of the above variables don't matter
# so long as they're different

def find_continumm(seed, node, row, gray, xyz, distance):
    stack = []
    add_to_stack = lambda tag, data : stack.append((tag, data))
    back_to_beginning = lambda : add_to_stack(beginning, None)
    back_to_beginning()
    while stack:
        tag, i = stack.pop()
        
        if tag is beginning:
            node_ravel = np.ravel_multi_index(node, xyz)
            if node_ravel in row or ~gray[node_ravel] or math.dist(node, seed) > distance:
                pass
            else:
                row.add(node_ravel)
                add_to_stack(entering_loop, 0)
                
        elif tag is entering_loop:
            if i < 3:
                if node[i] < xyz[i]:
                    node[i] += 1
                    add_to_stack(finishing_first_call, i)
                    back_to_beginning()
                else:
                    add_to_stack(enter_second_if, i)
                
        elif tag is finishing_first_call:
            node[i] -= 1
            add_to_stack(enter_second_if, i)
            
        elif tag is enter_second_if:
            if node[i] > 0:
                node[i] += 1
                add_to_stack(finishing_second_call, i)
                back_to_beginning()
            else:
                add_to_stack(increment_i, i)
                
        elif tag is finishing_second_call:
            node[i] -= 1
            add_to_stack(increment_i, i)
            
        elif tag is increment_i:
            add_to_stack(entering_loop, i + 1)  

If you take a look at the iterative version, you'll notice it very closely corresponds to the recursive version with the while-loop. Each tag corresponds to a specific line of code in this recursive version that we "jump back to".

Upvotes: 2

Related Questions