简体   繁体   English

将2D阵列复制到一维阵列中

[英]Copying a 2D array into a 1D array

I have a 2D array of 7 rows by 5 cols. 我有一个7行乘5列的2D数组。 I am trying to convert the 2D array into a 1D array but for some reason it will only copy the last element in every row or the full last column. 我正在尝试将2D数组转换为1D数组,但由于某种原因,它只会复制每行或最后一列的最后一个元素。

My 2D array looks like this : 我的2D数组看起来像这样:

0   33  32  37  0 
85  73  82  73  80 
104 103 95  109 101 
88  108 111 116 100 
133 119 102 122 116 
116 123 95  112 117 
0   57  76  58  0 

But the output of my 1D array is: 但是我的1D阵列的输出是:

0.0 80.0 101.0 100.0 116.0 117.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 .....

Here is my code : 这是我的代码:

public static void getTestImg() {
    TestImg = new double[35];
    double testValues;
    for (int r=0; r < TestPix.length; r++) {
        for (int c=0; c < TestPix[r].length; c++) {
            testValues = TestPix[r][c];
            TestImg[r] = testValues;
        }
    }
    for (int r=0; r < TestImg.length; r++) {
       System.out.print(TestImg[r] + " ");
    }
    System.out.println();
}

I've been trying to work out where I'm going wrong but I can't work out what is causing this. 我一直试图解决我出错的地方,但我无法解决导致这种情况的原因。 If I print "TestPix[r][c]" in the loop it is printing the elements in order so I don't know where the problem is. 如果我在循环中打印“TestPix [r] [c]”,它会按顺序打印元素,所以我不知道问题出在哪里。 Can anyone help? 有人可以帮忙吗?

You are copying to the wrong index of the output array ( r is the index of the current row of the source 2D array). 您正在复制到输出数组的错误索引( r是源2D阵列的当前行的索引)。 You need a different index variable : 您需要一个不同的索引变量:

int x = 0;
for (int r=0; r < TestPix.length; r++) {
    for (int c=0; c < TestPix[r].length; c++) {
        TestImg[x++] = TestPix[r][c];
    }
}

Assuming its N*N matrix, you could do something like: 假设它的N * N矩阵,您可以执行以下操作:

int N = board.length*board.length;
char[] board1D = new char[N];

int k = 0;
for (int i =0; i<board.length; i++) {
for (int j =0; j<board.length; j++) {
  board1D[k++] = board[i][j];
}
}

You can use Eran solution, or this is also common way how to do it : 您可以使用Eran解决方案,或者这也是常见的方法:

for (int r=0; r < TestPix.length; r++) {
    for (int c=0; c < TestPix[r].length; c++) {
        testValues = TestPix[r][c];
        TestImg[c + r*TestPix[r].length] = testValues;
    }
}

However this only works, if your array is rectangle (which in most cases is). 但是,只有当您的数组是矩形(在大多数情况下是这样)时,这才有效。

This is also "good to know", if you want count the index in 1D array with 2D indexes: 如果你想用2D索引计算1D数组中的索引,这也是“很有用”。

function index1D(int x, int y, int arrayColumnLength){
    return x*arrayColumnLength + y;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM