Finding the coordinations of n-th tile

Viewed 44

Lets say I have a group of tiles that have a 1:1 ratio which form a square. So 5x5, 10x10, 500x500, 2000x2000 etc.. How could I find the coordinations of the the nth tile I give? So lets say I want to find the 11th tile in a group of 5x5 tiles. The coordinations would be X=1 Y=3, but how can I find this out through a function?

Image illustrating which tile in a 5x5 grid

1 Answers

Assuming you wish top-to-bottom, left-to-right order, the following transforms are appropriate, all counted from zero:

Index n to coord:
x = n % w (w is the width of your rectangle in units)
y = n / w (rounding towards zero)

Coord to index:
n = w*y + x

If your indices start at 1, you have to replace n with n - 1 everywhere. If you count x, y starting with 1, replace x with x-1 and similarly for y. You may have to solve the resulting equation a bit, for example if all your indices start at 1 you'd end up with:

n - 1 = w*(y-1) + x-1

which solves to

n = w*(y-1) + x
Related