Search code examples
multidimensional-arrayiterationpseudocodeisometric

How to Iterate from back to front in a diamond-shaped isometric map


Imagine a diamond-shaped isometric map, which is basically a 2D array with (x,y) coordinates and the top cell as the origin, as marked in the cells:

Diamond

I want to iterate through these cells from back to front, in the following order:

 iteration order

What's the algorithm to loop in this way through an unknown same-sided map?

Expected output: [0,0], [0,1], [1,0], [0,2], [1,1], [2,0], [0,3], etc


Solution

  • python pseudocode:

    def iterate_cells(n):
        for i in range(n):
            for j in range(i+1):
                yield (j, i-j)
        for i in range(1, n+1):
            for j in range(n - i):
                yield(i+j, n-j-1)
    

    output:

    In [119]: list(iterate_cells(5))
    Out[119]: 
    [(0, 0),
     (0, 1),
     (1, 0),
     (0, 2),
     (1, 1),
     (2, 0),
     (0, 3),
     (1, 2),
     (2, 1),
     (3, 0),
     (0, 4),
     (1, 3),
     (2, 2),
     (3, 1),
     (4, 0),
     (1, 4),
     (2, 3),
     (3, 2),
     (4, 1),
     (2, 4),
     (3, 3),
     (4, 2),
     (3, 4),
     (4, 3),
     (4, 4)]