Skip to content
Advertisement

Index of center of mxn matrix. if center does not exist, return the index of the square closest to the center with the highest integer

Trying to write a method which returns the center of the MxN matrix and if the center does not exist the method should return the index of the square closest to the center with the highest integer value

Eg 1. –

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

return [1,2] (Center does not exist so closest to the center is [[0, 7, 0],[6, 3, 4]] and 7 is the max value)

Eg 2. –

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

return [1,2] (Center does not exist so closest to center is [[0,7],[6,3]] and 7 is the max value)

Eg 3. –

[[5, 7, 8],
 [0, 0, 7],
 [4, 6, 3]]

return [1,1] (Center exists)

private static int[] centerCoordinates(int[][] matrix) {
    int row = matrix.length;
    int col = matrix[0].length;
    if (row % 2 != 0 && col % 2 != 0 && row == col)
        return new int[]{row / 2, col / 2};
    if (row % 2 == 0 && col % 2 == 0 && row == col) {
        //calculate the max of internal square Eg 2.
        return new int[]{x, y};
    }
    //where row!=col
}

Advertisement

Answer

I’m assuming you made a mistake in example 1, you gave the right answer, but I think the cells considered should only be [[7],[3]] and not 3 columns wide.

Basically if the dimension is even check length/2-1 and length/2.

If the dimension is odd check only length/2.

Loop through and take max.

private static int[] centerCoordinates(int[][] matrix) {
    int row = matrix.length;
    int col = matrix[0].length;
    int[] ans = new int[]{row/2-(1-(row%2)), col/2-(1-(col%2))};
    int best = Integer.MIN_VALUE;
    for(int i=row/2-(1-(row%2));i<row/2+1;i++){
        for(int j=col/2-(1-(col%2));j<col/2+1;j++){
            if(matrix[i][j]>best){
                best = matrix[i][j];
                ans = new int[]{i,j};
            }
        }
    }
    return ans;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement