Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate row / col from grid position?

Given a grid where I know the number of rows (which is fixed), and I know the current count of columns (which can grow arbitrarily), how do I calculate the row and column of an square from it's index?

           +   +   +   +   +
 Cols ---> | 0 | 1 | 2 | 3 | ...
        +--+---|---|---|---|---
         0 | 0 | 3 | 6 | 9 | ...
        +--+---|---|---|---|---
 Rows    1 | 1 | 4 | 7 | A | ...
        +--+---|---|---|---|---
         2 | 2 | 5 | 8 | B | ...
        +--+---|---|---|---|---
         .   .   .   .   .   ...
         .   .   .   .   .   .
         .   .   .   .   .   .

So, given:

final int mRowCount = /* something */;
int mColCount;

And given some function:

private void func(int index) {

    int row = index % mRowCount;
    int col = ???

How do I correctly calculate col? It must be a function of both the number of columns and rows, I'm pretty sure. But my brain is failing me.

Sample: If index == 4, then row = 1, col = 1. If index == 2 then row = 2, col = 0.

Thanks.

like image 392
i_am_jorf Avatar asked Aug 23 '11 17:08

i_am_jorf


1 Answers

Didn't really understand your setup but if you got a normal grid with a progressive index like in the Android GridLayout:

 +-------------------+
 | 0 | 1 | 2 | 3 | 4 |
 |---|---|---|---|---|
 | 5 | 6 | 7 | 8 | 9 | 
 |---|---|---|---|---|
 | 10| 11| 12| 13| 14|
 |---|---|---|---|---|
 | 15| 16| 17| 18| 19| 
 +-------------------+

The calculation is:

int col = index % colCount;
int row = index / colCount;

For example:

row of index 6 = 6 / 5 = 1
column of index 12 = 12 % 5 = 2
like image 137
mbo Avatar answered Sep 20 '22 19:09

mbo