2
$\begingroup$

Looking for help in revising my algorithm. I need to find one that will give me the row and column of a cell on a grid.

The grid is $t \times t$. For example, this is a grid for $t=5$. Now given $n$, find the row and column. $$\begin{array}{|c|c|c|c|c|} 1& 2& 3& 4& 5\\ 6& 7& 8& 9& 10\\ 11& 12& 13& 14& 15\\ 16& 17& 18& 19& 20\\ 21& 22& 23& 24& 25 \end{array}$$

My attempt:

row: $n / t + 1$ column: $n \bmod t$

Second attempt:

$\operatorname{row}(x, t) = ((x-x \bmod t)/t)+1$

$\operatorname{column}(x,t) = (x-1) \bmod t+1$

Doesn't work for $n = t^2$

$\endgroup$

1 Answer 1

4
$\begingroup$

The row is :$$r = \lfloor \frac{n-1}{t} \rfloor + 1$$

The column is:$$c = n - t(r-1)$$

$\endgroup$
5
  • $\begingroup$ If zero indexing were to be used ($0,1,2,\ldots$ instead of $1,2,\ldots$) then the answer would look cleaner. $c$ could also be (n-1)%t+1. $\endgroup$
    – adam W
    Feb 26, 2013 at 16:23
  • $\begingroup$ Hi, I have another question. This was just borne out of curiosity. Is there an equation for reflections over diagonals? My attempt only works for the first column down when reflected over the topleft-bottomright diagonal. n - (row - 1)(t - 1) $\endgroup$ Feb 26, 2013 at 23:14
  • $\begingroup$ This is a common operation using matrices called the transpose, it is simply the swap of the indices $r\leftrightarrow c$. If by reflection over diagonals you mean other than the main (top left down to the bottom right), then maybe do some sort of shifting... though that sounds inexact, since any sort of "reflecting" would give indices out of bounds... $\endgroup$
    – adam W
    Feb 26, 2013 at 23:36
  • $\begingroup$ Indices? Is this a computer programming term? (ie, in for loops) I haven't started taking computer science courses yet. >.> $\endgroup$ Feb 26, 2013 at 23:39
  • $\begingroup$ yes, it is. The row index is $r$, the column index is $c$, and to transpose (reflection about the main diagonal) then swap those. $\endgroup$
    – adam W
    Feb 26, 2013 at 23:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .