有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

所以我的家庭作业要求我:

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

我尝试使用以下代码解决此问题:

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

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

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

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


共 (4) 个答案

  1. # 1 楼答案

    将2D数组的初始化更改为不包含第二个维度:new int[rows][]。现在,数组中有空数组。必须初始化循环中的那些:b[i]=new int[Math.min(columns,remainingCount)];,其中remainingCount是2d数组之外的数字量

  2. # 2 楼答案

    在方法中切换参数可能更好:

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

    允许使用vararg

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

    示例实现:

    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;
    }
    
  3. # 3 楼答案

    在代码中添加此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,即最终数组所需的确切大小

    然后,我们只需将最终阵列替换为这种大小的新阵列

  4. # 4 楼答案

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

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

    另见:How to populate a 2d array with values from a 1d array?