在给定索引的情况下获取三角矩阵的行和列 [英] Getting the Row and Column of a Triangular Matrix, Given the Index
问题描述
我正在使用具有以下形式的MxM三角矩阵:
I am working with a MxM triangular matrix which has the following form:
M = [m00 m10 m20 m30 m40]
[m11 m21 m31 m41 ]
[m22 m32 m42 ]
[m33 m43 ]
[m44 ]
如果更容易用索引来表示,则看起来像这样:
If it's easier to picture this in terms of indexes, it would look like this:
M = [0 1 3 6 10]
[2 4 7 11 ]
[5 8 12 ]
[9 13 ]
[14 ]
我知道这种索引方式可能看起来很奇怪,但是如果我能保留索引系统会更容易
I know this way of indexing might look odd but it would be much easier if I could keep the indexing system as it is in order for this module to work well with others.
我正在努力寻找一种算法,该算法采用矩阵的索引和大小,可以返回行和列,给定的索引属于。理想情况下,我将具有以下2种功能:
I am struggling with an algorithm that takes an index and size of the matrix that can return the row and column that the given index falls under. Ideally I would have 2 functions such as these:
int getRow (int index, int size);
int getCol (int index, int size);
所以 getRow(7,5)
返回 3
和 getCol(7,5)
会返回 1
我已经遇到了这个线程,但是我似乎无法修改给出的解决方案
I have come across this thread already but I cannot seem to modify the solution given there to work for the way I am indexing.
推荐答案
新答案
您可以找到行
和列
使用以下公式:
You can find the row
and column
using the following formulas:
int row = floor(-0.5 + sqrt(0.25 + 2 * index));
int triangularNumber = row * (row + 1) / 2;
int column = index - triangularNumber;
之所以有用,是因为每一行的第一项是三角数(0、1、3、6、10、15 ...)。因此,低于 index
的最大三角数为我们提供了 row
行。那么列
就是索引
与该三角形之间的差。
This works because the first item in each row is a triangular number (0, 1, 3, 6, 10, 15, ...). So the biggest triangular number that is lower than index
gives us the row
. Then column
is simply the difference between index
and that triangular number.
此外,请注意,您不需要参数 M
。
Also, note that you don't need the parameter M
.
旧答案
此代码将为您提供行
和索引
的列
。
This code will give you both the row
and column
of index
.
int triangularNumber = 0;
int row = 0;
while (triangularNumber + row < index) {
row ++;
triangularNumber += row;
}
int column = index - triangularNumber;
这篇关于在给定索引的情况下获取三角矩阵的行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!