Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...