採用小於等於或大於 3x3 的數組的二維數組構造函數

蒂姆·阿舍

從我的學位中得到一個項目,我被困在其中一個構造函數上。

  • 構造函數名稱需要如下所示Square3x3(int[][] array)
  • 它必須構造一個大小為 3x3 的二維數組,其值取自給定數組。
  • 如果給定數組的大小大於 3x3,則僅採用前 3x3 單元格。
  • 如果給定的數組較小,則其餘單元格將初始化為 -1。

請注意,給定的數組可能是非對稱的,甚至可能具有不同長度的行。

當且僅當給定數組中的相應單元格不存在時,確保將單元格初始化為 -1。

您可以假設數組不為空。

當給定的數組大於 3x3 時,以下代碼對我有用,但當它小於 3x3 時,我無法使其工作。

請注意,所有這些都需要與main.

感謝您的幫助。

我得到以下代碼:

public class Square3x3 {
        
    private int[][] Square3x3;
    
    public Square3x3(int[][]array) {
        Square3x3 = new int[3][3];
        int count =0;
        for (int i = 0; i < 3 && i < array.length; i++) {
            for (int j = 0; j < 3 && j < array[count].length; j++) {
                Square3x3[i][j] = array[i][j];
            }
            count++;
        }
    }
}
亞歷克斯·魯登科
  1. 構造一個 3x3 大小的結果數組並用 -1 填充它。
  2. 根據需要從輸入數組中復制值,選擇最小值 3 和輸入數組的行/列。
private int[][] square3x3 = {
    {-1, -1, -1},
    {-1, -1, -1},
    {-1, -1, -1}
};

public Square3x3(int[][] array) {
    for (int i = 0, n = Math.min(3, array == null ? -1 : array.length); i < n; i++) {
        for(int j = 0, m = Math.min(3, array[i] == null ? -1 : array[i].length); j < m; j++) {
            square3x3[i][j] = array[i][j];
        }
    }
}

因此,如果輸入的維度array小於 3x3,則在復制值時將使用 -1 的預填充值。

測試:

Square3x3 sq = new Square3x3(new int[3][2]); // input 2D arr initialized with 0
        
System.out.println(Arrays.deepToString(sq.square3x3));

// jagged input
sq = new Square3x3(new int[][]{{1, 2}, {3}, {4, 5, 6}});
System.out.println(Arrays.deepToString(sq.square3x3));
// input with nulls
mc = new MyClass(new int[][]{{1, 2}, null, {3}});
System.out.println(Arrays.deepToString(mc.square3x3));

輸出:

[[0, 0, -1], [0, 0, -1], [0, 0, -1]]
[[1, 2, -1], [3, -1, -1], [4, 5, 6]]
[[1, 2, -1], [-1, -1, -1], [3, -1, -1]]

為了解決當且僅當給定數組中的相應單元格不存在時單元格設置為 -1 的有點異想天開的要求,可以提供以下實現:

private int[][] square3x3;
public Square3x3(int[][] array) {
    square3x3 = new int[3][3]; // anyway an array filled with 0 is created
        
    for (int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            square3x3[i][j] = null != array    && i < array.length 
                           && null != array[i] && j < array[i].length
                            ? array[i][j] : -1;
        }
    }
}

該要求試圖以一種複雜/複雜的方式提供特定的實現,但這與預期的輸出無關,實際上需要遍歷循環中的所有 3x3 單元,而通過適當的初始化可以實現完全相同,並且可以跳過不相關的行/列.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章