简体   繁体   English

展平锯齿状2D阵列

[英]Flatten a Jagged 2D Array

I have an assignment that asks me to flatten a 2D array into a single array. 我有一项作业,要求我将2D数组展平为单个数组。

Here's what I have so far: 这是我到目前为止的内容:

public static int[] flatenArray(int [][] a){
    //TODO
    int length = 0;

    for(int y = 0; y < a.length; y++){
        length += a[y].length;
    }

    int[] neu = new int[length];

    int x = 0;
    for (int i = 0; i < a.length; i++){
        for(int j = 0; j < a[0].length; j++){
            neu[x] = a[i][j];
            x++;
        }
    }
    return neu;
}

When doing a JUnit Test for the following test case 在针对以下测试用例进行JUnit测试时

assertArrayEquals(new int[] {1,2,3,4,5,6,7,8,9,10,11},Ass06.flatenArray(new int[][] {{1,2,3},{4,5,6},{7,8,9,10,11}}));

I get the following error: 我收到以下错误:

arrays differed at element[9]; 数组在element [9]处有所不同; expected <10> but was <0> 预期为<10>,但为<0>

Somehow at the point where the array length of the 3rd "inner array" surpasses 3, the last 2 numbers ("10, 11") are not copied into the new array. 在第三个“内部数组”的数组长度超过3时,最后的2个数字(“ 10、11”)不会复制到新数组中。

There are multiple ways to solve this this, but it all comes down to you counting things wrong. 有多种方法可以解决此问题,但是这全都取决于您计算错了什么。

In a new int[1] , the first element is index 0. In an array of 1 element, .length will return 1 , but there will be no array[1] . new int[1] ,第一个元素为索引0。在1个元素的数组中, .length将返回1 ,但将没有array[1] That's why you're missing the the count by 1. 这就是为什么您将计数减去1的原因。

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

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