Search code examples
mathgridcoordinates

How to convert grid number to coordinates when the rows alternate order


7|8|9
6|5|4
1|2|3

1 -> (1,1)
2 -> (2,1)
3 -> (3,1)
4 -> (3,2)
5 -> (2,2)
6 -> (1,2)
7 -> (1,3)
8 -> (2,3)
9 -> (3,3)

In this grid, the mapping of the numbers to coordinates is shown above.

I'm struggling to come up with a formula where given the number of the grid and the number of rows and columns in the grid, it outputs the coordinates of the grid.

I tried following the logic in this question but in this question, the coordinate system starts from 0 and the rows are not alternating.


Solution

  • If there was no alternating and the numbers were all starting at 0 and not 1, then you could apply Euclidean division directly:

    x = n % 3
    y = n // 3
    

    where // gives the quotient of the Euclidean division, and % gives the remainder of the Euclidean division.

    If there was no alternating, but the numbers all start at 1 instead of 0, then you can fix the above formula by removing 1 from n to make it start at 0, then adding 1 to x and y to make them start at 1:

    x = ((n - 1) % 3) + 1
    y = ((n - 1) // 3) + 1
    

    Now all we have to change to take the alternating into account is to flip the x values on the right-to-left rows.

    y remains unchanged, and x remains unchanged on the left-to-right rows.

    The right-to-left rows are the rows with an even y, and you can flip x symmetrically around 2 by removing it from 4:

    if y % 2 == 0:
        x = 4 - x
    

    Putting it all together in a function and testing it, in python:

    def coord(n):
        y = ((n-1) // 3) + 1
        x = ((n-1) % 3) + 1
        if y % 2 == 0:  # right-to-left row
            x = 4 - x   # flip horizontally
        return (x, y)
    
    for n in range(1, 9+1):
        x, y = coord(n)
        print(f'{n} -> ({x},{y})')
    

    Output:

    1 -> (1,1)
    2 -> (2,1)
    3 -> (3,1)
    4 -> (3,2)
    5 -> (2,2)
    6 -> (1,2)
    7 -> (1,3)
    8 -> (2,3)
    9 -> (3,3)
    

    Inverse function

    The inverse operation of a Euclidean division is a multiplication and an addition:

    if y % 2 == 1:
        n = 3 * (y-1) + x
    else:
        n = 3 * (y-1) + 4 - x