Skip to content
Advertisement

Dividing a 1D array into a 2D array

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement