Coordinates to Grid Box Number
Asked Answered
T

3

5

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.

Tedmund answered 22/3, 2012 at 3:26 Comment(2)
Shouldn't (1,2) map to 5 ? (considering your co-ordinate system is centered at 0 and increments down and right)Solita
@Amit: He is writing (x,y) rather than (y,x). I understand your confusion though: in both matricies and computer-graphics, which count (0,0) as the upper-left element, the coordinates are written as (y,x).Dietitian
E
6

In this case, given cell index A in the range [0, 9), the row is given by R = floor(A/3) and the column is given by C = A mod 3.

In the general case, where MN cells are arranged into a grid with M rows and N columns (an M x N grid), given a whole number B in [0, MN), the row is found by R = floor(B/N) and the column is found by C = 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.

Ennoble answered 22/3, 2012 at 3:53 Comment(0)
D
5
cell = x + y*width

Programmers use this often to treat a 1D-array like a 2D-array.

Dietitian answered 22/3, 2012 at 15:27 Comment(0)
N
0

For future programmers

May this be useful:

let wide = 4;
let tall = 3;
let reso = ( wide * tall);

for (let indx=0; indx<reso; indx++)
{
    let y = Math.floor(indx/wide);
    let x = (indx % wide);
    console.log(indx, `x:${x}`, `y:${y}`);
};
Namnama answered 3/3, 2022 at 10:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.