Home > Mobile >  How to check if all lines in a 2d int array have the same length?
How to check if all lines in a 2d int array have the same length?

Time:11-28

If I have a 1D array, I can easily check the length of the row with with a.length. In a 2D array, I can check the length of all columns with something like this

int[][] a = {{5,3,4,6,7,8,9,1,2},
             {6,7,2,1,9,5,3,4,8},
             {1,9,8,3,4,2,5,6,7},
             {8,5,9,7,6,1,4,2,3},
             {4,2,6,8,5,3,7,9,1},
             {7,1,3,9,2,4,8,5,6},
             {9,6,1,5,3,7,2,8,4},
             {2,8,7,4,1,9,6,3,5}};
for (int k = 0; k < a.length; k  ) {
    if (a[k].length != 9) return false
}

I am not even sure if that is correct. How can I check the different rows? When I have a 4x4 matrix, and the last row only contains 3 values instead of 4, how can I find that out?

CodePudding user response:

(Semicolon missing after false.) Your code is correct. If you get passed an int[][] a of unknown size:

boolean isRectangularMatrix(int[][] a) {
    int columnCount = 0; // Maybe interesting too.
    boolean rectangular = true;
    if (a.length != 0) {
        columnCount = a[0].length;
        for (int k = 1; k < a.length; k  ) {
            if (a[k].length != columnCount) {
                //return false; // Or:
                rectangular = false;
                break;
            }
        }
    }
    return rectangular;
}

boolean isSquareMatrix(int[][] a) {
    int columnCount = 0; // Maybe interesting too.
    boolean square = true;
    if (a.length != 0) {
        columnCount = a[0].length;
        if (a.length != columnCount) {
            square = false;
        } else {
            for (int k = 1; k < a.length; k  ) {
                if (a[k].length != columnCount) {
                    //return false; // Or:
                    square = false;
                    break;
                }
            }
        }
    }
    return square;
}

You do not need a check if the array is created correspondingly:

int[][] a = new int[M][N];
  • Related