简体   繁体   中英

How do I convert a ragged 2D array to a rectangular 2D array?

Create a method cleanMatrix , that takes a ragged 2D int array, and returns a rectangular array with the same values.

For example:

Input:

{{1, 2, 3, 3, 1, 7},
{6, 8, 7, 1},
{2, 3, 4, 5, 11},
{12}}

Output:

{{1, 2, 3, 3, 1, 7},
{6, 8, 7, 1, 0, 0},
{2, 3, 4, 5, 11, 0},
{12, 0, 0, 0, 0, 0}}

If you have to make a jagged 2d array rectangular , you can use Arrays.copyOf method for each row and specify a new length:

int length = 6;
int[][] jagged = {
        {1, 2, 3, 3, 1, 7},
        {6, 8, 7, 1},
        {2, 3, 4, 5, 11},
        {12}};

int[][] rectangular = Arrays
        .stream(jagged)
        .map(row -> Arrays.copyOf(row, length))
        .toArray(int[][]::new);

Arrays.stream(rectangular).map(Arrays::toString).forEach(System.out::println);
//[1, 2, 3, 3, 1, 7]
//[6, 8, 7, 1, 0, 0]
//[2, 3, 4, 5, 11, 0]
//[12, 0, 0, 0, 0, 0]

Int arrays are initialized with 0, so you simply could extend the sub arrays when needed. A solution could look somewhat like this (untested).

int[][] source = <your source array>;

final int neededSize = <length you want extend the subs to>;

for(int i = 0; i < source.length; i++){
    if(source[i].length < neededSize){
        source[i] = getExtendedArray(source[i]);
    }
}

int[] getExtendedArray(int[] originalArr){
    int[] tempArr = new int[neededSize];
    for(int x = 0; x < originalArr.length; x++){
        tempArr[x] = originalArr[x];
    }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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