Search code examples
recursionsplittreeiterationdepth

Iterating a recursive split of defined depth


I have two vertices (a) and (b) and I want to recursively split them at their midpoints.

The pattern looks like this:

enter image description here

For this specific depth I can write it like this:

       a_b = self.abfn(   a,    b)

      ab_b = self.abfn( a_b,    b)
      a_ab = self.abfn(   a,  a_b)
    
     abb_b = self.abfn(ab_b,    b)
    ab_abb = self.abfn( a_b, ab_b)
     a_aab = self.abfn(   a, a_ab)
    aab_ab = self.abfn(a_ab,  a_b)

However I want to write it such that I can define a depth and repeatedly split to that depth. The one caveat is I do not want to use recursive functions

How can I iterate in this manner?

I'm using python but the language doesn't really matter.


Solution

  • You could use this code:

    def midpoint(a, b):
        return ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
    
    def abfn(a, b, depth):
        vertices = [a, b]
        for _ in range(depth):
            nextlevel = vertices[:1]
            for a, b in zip(vertices, vertices[1:]):  # all consecutive pairs
                mid = midpoint(a, b)
                nextlevel.extend((mid, b))
            vertices = nextlevel
        return vertices
    

    Example call:

    a = (0, 100)
    b = (0, 200)
    vertices = abfn(a, b, 2)
    
    print(vertices)
    

    Output:

    [(0, 100), (0.0, 125.0), (0.0, 150.0), (0.0, 175.0), (0, 200)]