开发者

How to convert 1D array to 2D by column major

say I have a 1D array like int[] x = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}.

I would like to conver it into 2D where it looks like:

1 5  9 13  
2 6 10 14  
3 7 11 15  
4 8 12 16  

Currently, I have

for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < Nb; j++)开发者_Python百科
        s[i][j] = x[i + j];
}

However, that doesnt work. How would I do this?


Try

for (int i = 0, k=0; i < 4; i++)
  for (int j = 0; j < Nb; j++)
    s[j][i] = x[k++]; // you may want s[i][j]


I assume that stray 7 was a typo?

Since we want the inner loop to move downward, and the outer to move rightward, you can do this:

for i in (0..width)
   for j in (0..height)
      s[j][i] = x[i*height+j]

Tracing this out illustrates why it works:

s[0][0] = x[0*4+0] = x[0]
s[1][0] = x[0*4+1] = x[1]
...
s[0][1] = x[1*4+1] = x[5]


No clue what Nb is, but you're way off on reading the initial array. Try something like this:

for (int i = 0; i < 4; i++)
    for (int j = 0; j < 4; j++)
        s[j][i] = x[i*4 + j];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜