Find the grid number of a X,Y coordinate

82 Views Asked by At

Let's say we have a grid separated in chunks. Each chunk contains multiple points.

Grid and chunks

Each chunk has a number :

Chunks numbers

Let's say we have a point X,Y, how do we find its grid number based on its coordinate?

Find the chunk number

1

There are 1 best solutions below

1
On BEST ANSWER

This problem is easily solved when you consider integer division and modulus. The grid is covered in tiles of size $n \times n$ , and the tiles are set up so that they also form a grid of size $m \times m$. Therefore, in order to build this tiling, you only need to know the integers $n$ and $m$.

The easiest approach to figuring out the tile number is to switch from base $10$ to base $m$ (in your example, $m=4$). With this approach, the tile number for points with $x=0$ will always have last digit $0$ in base $m$. This is actually not only true for $x=0$ but $x=0, 1, \ldots , n-1$ (width of the tile). I recommend that you pause to think about this and consider some example points, referring to the picture.

Similarly, the tile number for points with $x=n, n+1, \ldots 2n-1$ will always have last digit $1$ in base $m$. We immediately see the following pattern: the last digit of the tile number in base $m$ can be extracted by integer dividing the $x$-coordinate by the width of the tile; $$ \text{last digit in base }m = \frac{x}{n} \qquad \text{(integer division)} $$

The remaining question is to figure out the first digit(s) of the tiling number. This, of course can be extracted from the $y$-coordinate, and we see that $$ \text{first digit(s) in base }m = \frac{y}{n} \qquad \text{(integer division)} $$ Let's now combine these equations to auxiliary quantities: $$ f = \frac{y}{n} \qquad s = \frac{x}{n} \qquad \text{(integer division)} $$ We need to convert this back to base 10, and the answer becomes

$$ \text{Tile number} = mf + s $$

Let's take a numerical example. In your picture, $n=2$ and $m=4$. Therefore $$ (x,y) = (5,3) \Rightarrow \left\{ \begin{array}{cc} f = 3/2 = 1 \\ s = 5/2 = 2 \end{array} \right. \Rightarrow mf+s = 4\times 1 + 2 = 6 $$ Second example: $$ (x,y) = (0,7) \Rightarrow \left\{ \begin{array}{cc} f = 7/2 = 3 \\ s = 0/2 = 0 \end{array} \right. \Rightarrow mf+s = 4\times 3 + 0 = 12 $$ Our approach seems to work.