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.

Community
  • 1
  • 1
Rick Button
  • 1,212
  • 13
  • 19
  • Shouldn't (1,2) map to 5 ? (considering your co-ordinate system is centered at 0 and increments down and right) –  Mar 22 '12 at 03:43
  • @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)`. – BlueRaja - Danny Pflughoeft Mar 22 '12 at 15:25

3 Answers3

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.

andand
  • 17,134
  • 11
  • 53
  • 79
5
cell = x + y*width

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

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
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}`);
};
argon
  • 449
  • 4
  • 11