如何从行和列计算索引?

How to calculate index from row and column?

我想为任何给定的行和列计算一个索引(以 0 为底),其中行和列以 1 为底并且列数已知,例如2

如果max_columns为2,索引为5,则根据索引计算行号:

Row = (index % max_columns) + (int)(index / max_columns)
    = (5 % 2) + (int)(5 / 2)
    = 1 + 2
    = 3

根据索引计算列号

Col = max_columns - (index % max_columns)
    = 2 - (5 % 2)
    = 2 - 1
    = 1

问题是如何从索引以 0 为基数的任何索引计算行和列。这是在 java 应用程序中计算数组的索引。

'Willem Van Onsem' 为我提供的正确解决方案:

其中 Row 为 3,Col 为 2,max_columns 为 2:

Index = (Row * max_columns) + Col - max_columns - 1
      = (3 * 2) + 2 - 2 - 1
      = 6 + (-1)
      = 5

鉴于每一行由 n 列组成,列和行的从零开始的索引为:

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

现在,由于您的 rowcol 偏移 1,您只需将 1 添加到两者即可:

int row1 = (index/n)+1;
int col1 = (index%n)+1;

对于反函数,如果rowcol偏移0,可以计算索引为:

int index = row*n+col;

或者如果索引偏移 1:

int index = row1*n+col1-n-1;
row = (int) (index / max_columns + 1)
col = (index % max_columns + 1)