Math 如何从网格位置计算行/列?

Math 如何从网格位置计算行/列?,math,language-agnostic,Math,Language Agnostic,给定一个网格,其中我知道行数(固定),我知道当前列数(可以任意增长),如何从它的索引计算正方形的行和列 + + + + + Cols ---> | 0 | 1 | 2 | 3 | ... +--+---|---|---|---|--- 0 | 0 | 3 | 6 | 9 | ... +--+---|---|---|---|--- Rows 1 | 1 | 4 | 7 | A | ...

给定一个网格,其中我知道行数(固定),我知道当前列数(可以任意增长),如何从它的索引计算正方形的行和列

           +   +   +   +   +
 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
?我敢肯定,它一定是列数和行数的函数。但是我的大脑让我失望了

示例:如果
索引==4
,则
行=1
列=1
。如果
索引==2
,则
行=2
列=0


谢谢。

int col=index/mRowCount

我相信该列将通过整数除法获得:

int col = index / mRowCount;
column = index / max_rows;
row    = index % max_rows;
将其替换为乘法和减法,可以将其限制为单除法(消除模运算)。我不确定这是否成本更低;在大多数情况下可能都无关紧要:

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

index=col*mRowCount+行

然后

row=索引%mRowCount

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

col=索引/mRowCount

行=索引/numberOfColumns

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


column=index%numberOfColumns

并不真正了解您的设置,但是如果您使用的是一个普通的网格,它具有类似于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
天花板向上舍入到下一个整数

col = MOD(index / numberOfColumns)
除此之外,您必须考虑一个例外-->当MOD=0时,当col结果为零时,然后设置
col=numberOfColumns

(比如说,
numberOfColumns=48
…那么,
MOD(96,48)
是零,
MOD(48,48)也是零。)=0
…因为任何可以被48整除的东西都是MOD=0…换句话说,当MOD=0时,你在最后一列或最高一列,你在numberOfColumns列

好的,现在,如果我想要分页呢?我想要最多,比如说每页3行。因此,对于上面的内容,行
1,2,3
将在第1页,行
4
将在第2页。我希望
int row=..
公式为
15..19
返回
1