将二维上三角和下三角中的元素映射到线性结构
我有一个 NxN 维度的矩阵 M,其中 M(i,j) = M(j,i)
我想将此结构表示为 (N²+N)/2 线性数组 K,以节省空间。我的问题是提出将 M(min(i,j),min(i,j)) 映射到范围 [0,(N^2)/2) 的公式
下面是 3x3 矩阵的映射对于 K 线性数组的索引,X 意味着这些单元不存在,而是使用它们的转置:
0123
X456
XX78
XXX9
这是一个 7x7 矩阵,其中包含 K 线性数组的索引,
0 1 2 3 4 5 6
0 00 01 02 03 04 05 06
1 07 08 09 10 11 12
2 13 14 15 16 17
3 18 19 20 21
4 22 23 24
5 25 26
6 27
目前我有以下内容
int main()
{
const unsigned int N = 10;
int M[N][N];
int* M_ = &(M[0][0]);
assert(M[i][j] = M_[N * min(i,j) + max(i,j)]);
//int* K = .....
//assert(M[i][j] = K[.....]);
return 0;
}
I have a matrix M which is of NxN dimensions, where M(i,j) = M(j,i)
I would like to represent this structure as a (N²+N)/2 linear array K, to save space. My problem is coming up with the formula that will map a M(min(i,j),min(i,j)) into a range [0,(N^2)/2)
Below is a mapping of a 3x3 matrix with indexes for K linear array, the X means those cells don't exist and instead their transpose is to be used:
0123
X456
XX78
XXX9
Here is a 7x7 matrix with indexes for the K linear array
0 1 2 3 4 5 6
0 00 01 02 03 04 05 06
1 07 08 09 10 11 12
2 13 14 15 16 17
3 18 19 20 21
4 22 23 24
5 25 26
6 27
at the moment I have the following
int main()
{
const unsigned int N = 10;
int M[N][N];
int* M_ = &(M[0][0]);
assert(M[i][j] = M_[N * min(i,j) + max(i,j)]);
//int* K = .....
//assert(M[i][j] = K[.....]);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是正确的映射:
其中
sum(x) = x * (x + 1) / 2;
Here's the correct mapping:
where
sum(x) = x * (x + 1) / 2;
朝我需要的相反方向走:
To go the opposite direction which is what I needed:
假设 y >= x,您可以使用“映射”,这样
会产生“
如果 x>y,则只需交换 x 和 y”。为此,您需要 (size+1)*size/2 个元素空间。
Assuming y >= x, you could use a "mapping" like
which would produce
If x>y, just swap x and y. You need (size+1)*size/2 elements space for this.