Copying a 1d array to a 2d array

瘦欲@ 提交于 2021-02-05 07:32:05

问题


So I have homework that asked me to:

Write a method that takes two parameters: an array of integers and an integer that represents a number of elements. It should return a two-dimensional array that results from dividing the passed one-dimensional array into rows that contain the required number of elements. Note that the last row may have less number of elements if the length of the array is not divisible by the required number of elements. For example, if the array {1,2,3,4,5,6,7,8,9} and the number 4 are passed to this method, it should return the two-dimensional array {{1,2,3,4},{5,6,7,8},{9}}.

I tried to solve it using this code:

public static int[][] convert1DTo2D(int[] a, int n) {
    int columns = n;
    int rows = a.length / columns;
    double s = (double) a.length / (double) columns;
    if (s % 2 != 0) {
        rows += 1;
    }
    int[][] b = new int[rows][columns];
    int count = 0;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            if (count == a.length) break;
            b[i][j] = a[count];
            count++;
        }
    }
    return b;
}

But I had a problem which is when I try to print the new array this is the output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 0]]

So how can I remove the 3 zeros at the end? Just a note that I can't use any method from java.util.* or any built-in method to do this.


回答1:


Change the 2D array's initialization to not contain the second dimension: new int[rows][]. Your array now has null arrays inside it. You have to initialize those in your loop: b[i]=new int[Math.min(columns,remainingCount)]; where remainingCount is the amount of numbers outside the 2d array.




回答2:


Populating a 2d array with values from a 1d array as long as they are present:

public static int[][] convert1DTo2D(int[] arr, int n) {
    // row count
    int m = arr.length / n + (arr.length % n == 0 ? 0 : 1);
    // last row length
    int lastRow = arr.length % n == 0 ? n : arr.length % n;
    return IntStream.range(0, m)
            .mapToObj(i -> IntStream.range(0, i < m - 1 ? n : lastRow)
                    .map(j -> arr[j + i * n])
                    .toArray())
            .toArray(int[][]::new);
}
public static void main(String[] args) {
    int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int[][] arr2 = convert1DTo2D(arr1, 4);

    System.out.println(Arrays.deepToString(arr2));
    // [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
}

See also: How to populate a 2d array with values from a 1d array?




回答3:


It may be better to switch arguments in the method:

int[][] convert1DTo2D(int cols, int... arr)

to allow use of vararg.

Also, it is possible to iterate on the input array (single loop) instead of nested loops.

Example implementation:

public static int[][] convert1DTo2D(int cols, int... a) {
    int lastRowCols = a.length % cols;
    int rows = a.length / cols;

    if (lastRowCols == 0) {
        lastRowCols = cols;
    } else {
        rows++;
    }

    int[][] b = new int[rows][];

    for (int i = 0; i < a.length; i++) {
        int r = i / cols;
        int c = i % cols;
        if (c == 0) { // start of the row
            b[r] = new int[r == rows - 1 ? lastRowCols : cols];
        }
        b[r][c] = a[i];
    }
    return b;
}



回答4:


Adding this if-condition to your code will shorten the final array should it not be the right size:

...
final int[][] b = new int[rows][columns];

if ((a.length % columns) != 0) {
    b[rows - 1] = new int[a.length % columns];
}

int count = 0;
...

% is the Modulo operator which gives you the remainder of a division of the first and second number.

9 % 4 would return 1, the exact size needed for our final array.

We then merely have to replace the final array with a new one of that size.



来源:https://stackoverflow.com/questions/65036389/copying-a-1d-array-to-a-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!