2011-08-23 21 views
10

給定一個網格,我知道行數(這是固定的),並且我知道當前的列數(可以隨意增長),我如何從它的索引計算正方形的行和列?如何從網格位置計算行/列?

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

因此,考慮到:

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

而且給出了一些功能:

private void func(int index) { 

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

如何正確計算col?它必須是列數和行數的函數,我很確定。但是我的大腦讓我失望了。

樣本:如果index == 4,則row = 1,col = 1。如果index == 2row = 2,col = 0

謝謝。

回答

7

int col = index/mRowCount;

4

相信列將通過整數除法來獲得:

int col = index/mRowCount; 

這將有可能將其限制在一個單一的除法(消除模運算)通過用乘法代替它和減法。我不確定這是否便宜;可能不會在大多數情況下重要:

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

index = col * mRowCount + row

然後

row = index % mRowCount;

col = index/mRowCount;

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

行=指數/ numberOfColumns

列=索引%numberOfColumns

1

並沒有真正理解你的設置,但如果你有一個正常電網與逐行掃描的指標像在Android GridLayout

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

計算是:

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

例如:

row of index 6 = 6/5 = 1 
column of index 12 = 12 % 5 = 2