Given a NxN grid and an integer calculate the row and column

430 Views Asked by At

I know this is most likely elementary school math, but I am having hard time finding a good algorithm. Given a NxN grid and a number which represents the nth tile counting left to right like a typewriter, where at the end of the row you return to column 1... e.g. given a grid of 20x20 and the number is 21, 21 would be located in column 1 row 2. Another example 36 in a 20x20 grid would be column 16 row 2. And so on.

What is the formula I can use to find the row and column.

I tried using modulo to find the column and division for the row, but it just does not work yet.

1

There are 1 best solutions below

4
On BEST ANSWER

Let's do a similar problem, where you have indices starting from $0$. In other words, you have a grid with $m$ rows and $n$ columns and you need to find the index of some number.

For simplicity let's look at $n=10$ first, letting $m=30$. Then, entry $0$ maps to $(0,0)$, and we follow with similar relationships below:

  • $0 \mapsto 0,0$
  • $1 \mapsto 0,1$
  • \ldots
  • $9 \mapsto 0,9$
  • $10 \mapsto 1,0$
  • \ldots
  • $19 \mapsto 1,9$

This may be enough to get the pattern. The entry number $N$ maps the second coordinate as $N \pmod{10}$ and the first coordinate is $\lfloor N \div 10 \rfloor$ which we will for convenience denote $N//10$.

In full generality, we map $N \mapsto N//n,N \pmod n$.


The problem you posed is slightly more tricky, since indexing is $1$-based, so given $N$ you translate it to the $N$ from the above problem by subtracting one, then map, and add 1 to compensate, so you get $$ N \mapsto 1 + [(N-1)//n], 1+[(N-1) \pmod n] $$


Useful to note that on most computing systems, the first operation is denoted div and the second mod. In addition, some have the faster divmod which does both.