开发者

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.


int col = index / mRowCount;


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


index = col * mRowCount + row

then

row = index % mRowCount;

col = index / mRowCount;


I believe the column would be obtained by integer division:

int col = index / mRowCount;

It would be possible to limit it to a single division (eliminate the modulus operation) by replacing it with a multiplication and subtraction. I'm not sure if that is less costly; probably wouldn't matter in most situations:

int col = index / mRowCount;
int row = index - col * mRowCount;


row = CEILING(index / numberOfColumns)    

CEILING rounds up to the next integer

col = MOD(index / numberOfColumns)

 and this with one exception which you must take into account -->  when MOD=0, when col result is ZERO, then you set  your  col=numberOfColumns (so for example, let say numberOfColumns=48... then,  MOD(96, 48) is ZERO, and so is  MOD(48, 48)=0  ... cause anything divisible by 48 will be MOD=0...  in other words, when MOD=0 you are in the LAST or HIGHEST column, you are in numberOfColumns column


column = index / max_rows;
row    = index % max_rows;


row = index / numberOfColumns

and

column = index % numberOfColumns

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜