Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

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.

share|improve this question
    
I don't understand your examples. Did you mean a 3 x 3 grid? –  AMPerrine Oct 27 '11 at 19:54
    
Sorry, yes, a 3 x 3 grid = 9 elements. I will change. –  Brian Reindel Oct 27 '11 at 19:55

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer

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)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.