2
$\begingroup$

Assume a 3 x 3 grid, but the elements are actually contained in a zero-based index array. So I know if I'm on element 5, I'm in row 2, and if I'm on element 7 then I'm in row 3. How would I actually calculate this? Please feel free to modify the title's terminology if I'm not using it correctly. Also, I would very much appreciate the logic used to determine the formula for the answer, as I'm not a mathematician.

  • 0
    Sorry, yes, a 3 x 3 grid = 9 elements. I will change.2011-10-27

2 Answers 2

3

As you start with zero, I assume the element number k="3" is the first one in the second row. You get the row with

$r=\lfloor k/3 \rfloor + 1$

and the column with

$m = (k \text{ mod } 3) + 1$

Where I used the floor and the mod functions.

1

The logic used is fairly simple. If you have a 3 by 3 grid, starting at 0, the elements would look as:

0 1 2
3 4 5
6 7 8

You count from left to right, until the number of columns matches the number of columns the grid has, then start again with the next row.

Mathematically, the row is floor(elementNumber / numberOfRows) I.E.: element 4 would be floor(4 / 3) = 1.33 = 1; which is actually row 2 (0 indexed remember?)

The Column would be elementNumber mod numberofColumns. IE, element 4: 4 mod 3 = 1; which is actually column 2 (0 indexed)