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

i_a*_*orf 10 language-agnostic math

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

           +   +   +   +   +
 Cols ---> | 0 | 1 | 2 | 3 | ...
        +--+---|---|---|---|---
         0 | 0 | 3 | 6 | 9 | ...
        +--+---|---|---|---|---
 Rows    1 | 1 | 4 | 7 | A | ...
        +--+---|---|---|---|---
         2 | 2 | 5 | 8 | B | ...
        +--+---|---|---|---|---
         .   .   .   .   .   ...
         .   .   .   .   .   .
         .   .   .   .   .   .
Run Code Online (Sandbox Code Playgroud)

所以,给定:

final int mRowCount = /* something */;
int mColCount;
Run Code Online (Sandbox Code Playgroud)

并给出一些功能:

private void func(int index) {

    int row = index % mRowCount;
    int col = ???
Run Code Online (Sandbox Code Playgroud)

我该如何正确计算col?它必须是列数和行数的函数,我很确定.但是我的大脑让我失望了.

示例:如果index == 4,那么row = 1,col = 1.如果index == 2那时row = 2,col = 0.

谢谢.

And*_*nck 7

int col = index / mRowCount;


Gre*_*osz 5

index = col * mRowCount + row

然后

row = index % mRowCount;

col = index / mRowCount;


Mar*_*ius 5

并不是很了解您的设置,但是如果您有一个带有渐进式索引的普通网格(例如在Android中)GridLayout

 +-------------------+
 | 0 | 1 | 2 | 3 | 4 |
 |---|---|---|---|---|
 | 5 | 6 | 7 | 8 | 9 | 
 |---|---|---|---|---|
 | 10| 11| 12| 13| 14|
 |---|---|---|---|---|
 | 15| 16| 17| 18| 19| 
 +-------------------+
Run Code Online (Sandbox Code Playgroud)

计算公式为:

int col = index % colCount;
int row = index / colCount;
Run Code Online (Sandbox Code Playgroud)

例如:

row of index 6 = 6 / 5 = 1
column of index 12 = 12 % 5 = 2
Run Code Online (Sandbox Code Playgroud)