Search code examples
algorithmmathlayoutformulaalgebra

Convert incremental grid index to (x,y) coordinates


I'm desperately looking for the expressions giving me x and y for each i, ordered in this manner:

grid to coordinates

x = f(i) ??
y = f(i) ??

I'm coding in GLSL so I have access to basic math functions (modulo, floor, square root...) as well as if/else statements. I only have access to the i variable though.


Solution

  • I do not know GLSL but here is code in Python 3. This should be easy to convert to other languages. (You could use floor rather than int here.) This version uses Python to return two output values x and y for one input value i. In Python 3 the line from math import sqrt would be needed at the top of the code.

    def f(i):
        base = int(sqrt(i))
        remains = i - base * base
        if remains <= base:
            x = remains
            y = base
        else:
            x = base
            y = 2 * base - remains
        return x, y