从行和列计算索引 [英] Calculate Index from row and column

查看:93
本文介绍了从行和列计算索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to calculate an index (base 0) for any given row and column where rows and columns are base 1 and the number of columns is known, e.g 2

如果max_columns为2且index为5,则从索引计算行号:

If max_columns is 2 and index is 5, then to calculate row number from an index:

    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应用程序中数组的索引。

Question is how to calculate row and column from any index where the index is base 0. This is to calculate an index into an array in a java application.

由'Willem Van Onsem'提供给我的正确解决方案

The correct solution for me as supplied by 'Willem Van Onsem'

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

Where Row is 3, Col is 2 and max_columns is 2:

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


推荐答案

鉴于每一行都包含 n 列,零 - 列和行的基于索引的是:

Given every row consists out of n columns, the zero-based index for the column and row are:

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

现在,因为你的 col 是抵消 1 ,你只需将 1 添加到两者:

Now since your row and col are offset 1, you simply add 1 to both:

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






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


For the inverse function, if row and col are offset 0, you can calculate the index as:

int index = row*n+col;

或索引是否偏移 1

int index = row1*n+col1-n-1;

这篇关于从行和列计算索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆