Translate sequentially assigned number in grid to x-y coordinates
Say I have a grid of 5x5, with each cell in the grid numbered from 0-24, going from left to right. Given a cell number such as 17, how do I determine that cell's x and y coordina开发者_JS百科tes? I've been able to do it vice versa, where if given the coordinates I can calculate cell number:
Cellnumber = x + y∗width
But now I want the opposite. Any ideas?
Assuming 0-based coordinates and a C-like syntax, it would be something like this:
int y = Cellnumber / width;
int x = Cellnumber % width;
With the notation that %
is the modulus operator:
x = Cellnumber % width
y = Floor(Cellnumber / width)
So in your 5 x 5 example, Cellnumber
= 17
x = 2
y = 3
I think:
Y = (cellnum / 5) + 1
X = (cellnum % 5) + 1
精彩评论