Let’s say I have some grid that looks like this
_ _ _ _ _ _ _ _ _
| | | |
| 0 | 1 | 2 |
|_ _ _|_ _ _|_ _ _|
| | | |
| 3 | 4 | 5 |
|_ _ _|_ _ _|_ _ _|
| | | |
| 6 | 7 | 8 |
|_ _ _|_ _ _|_ _ _|
How do I find which cell I am in if I only know the coordinates? For example, how do I get 0 from (0,0), or how do I get 7 from (1,2)?
Also, I found this question, which does what I want to do in reverse, but I can’t reverse it for my needs because as far as I know there is not a mathematical inverse to modulus.
In this case, given cell index
Ain the range [0, 9), the row is given byR = floor(A/3)and the column is given byC = A mod 3.In the general case, where
MNcells are arranged into a grid withMrows andNcolumns (anM x Ngrid), given a whole number B in [0, MN), the row is found byR = floor(B/N)and the column is found byC = B mod N.Going the other way, if you are given a grid element (R, C) where R is in [0, M) and C is in [0, N), finding the element in the scheme you show is given by
A = RN + C.