Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c++ - Mapping elements in 2D upper triangle and lower triangle to linear structure

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 (N2+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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To go the opposite direction which is what I needed:

void printxy(int index)  
{  
    int y = (int)((-1+sqrt(8*index+1))/2);  
    int x = index - y*(y+1)/2;  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...