'Coordinates to Grid Box Number

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.



Solution 1:[1]

cell = x + y*width

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

Solution 2:[2]

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}`);
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BlueRaja - Danny Pflughoeft
Solution 2