繁体   English   中英

将一维数组划分为二维数组

[英]Dividing a 1D array into a 2D array

所以我有作业要求我:

编写一个带有两个参数的方法:一个整数数组和一个代表多个元素的 integer。 它应该返回一个二维数组,该数组是将传递的一维数组分成包含所需元素数量的行。 请注意,如果数组的长度不能被所需的元素数量整除,则最后一行的元素数量可能会更少。 例如,如果将数组{1,2,3,4,5,6,7,8,9}和数字4传递给此方法,它应该返回二维数组{{1,2,3,4},{5,6,7,8},{9}}

我尝试使用以下代码解决它:

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;
}

但是我遇到了一个问题,当我尝试打印新数组时,这是 output:

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

那么我怎样才能删除最后的 3 个零呢? 请注意,我不能使用java.util.*中的任何方法或任何内置方法来执行此操作。

将二维数组的初始化更改为不包含第二维: new int[rows][] 您的阵列现在内部有 null arrays。 您必须在循环中初始化它们: b[i]=new int[Math.min(columns,remainingCount)]; 其中剩余计数是二维数组之外的数字数量。

如果最终数组的大小不合适,则将此 if 条件添加到您的代码中将缩短它:

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

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

int count = 0;
...

%是模运算符,它为您提供第一个和第二个数字除法的余数。

9 % 4将返回 1,即我们最终数组所需的确切大小。

然后,我们只需要用该大小的新数组替换最终数组。

在方法中切换arguments可能会更好:

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

允许使用可变参数。

此外,可以迭代输入数组(单循环)而不是嵌套循环。

示例实现:

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;
}

用一维数组中的值填充二维数组,只要它们存在:

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]]
}

另请参阅:如何使用 1d 数组中的值填充 2d 数组?

暂无
暂无

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

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