【问题标题】:How to calculate index from row and column?如何从行和列计算索引?
【发布时间】:2016-03-02 13:39:21
【问题描述】:

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

如果 max_columns 为 2 且 index 为 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

【问题讨论】:

  • 以上公式计算 RowCol 计算 - afaik - 不正确的行和列。

标签: language-agnostic


【解决方案1】:

鉴于每一行由 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;

【讨论】:

  • 你能把 ( 和 ) 添加到 index/n+1 吗?
【解决方案2】:
row = (int) (index / max_columns + 1)
col = (index % max_columns + 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    相关资源
    最近更新 更多