How to inverse N x M matrix in Java

1 Answer

0 votes
public class MatrixDemo {

    public static void printMatrix(int[][] matrix) {
        int rows = matrix.length;          // number of rows
        int cols = matrix[0].length;       // number of columns

        for (int i = 0; i < rows; i++) {
            StringBuilder row = new StringBuilder();
            for (int j = 0; j < cols; j++) {
                // Pad each number to width 4
                row.append(String.format("%4d", matrix[i][j]));
            }
            System.out.println(row);
        }
    }

    public static void inverseMatrix(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int counter = 0;

        for (int i = 0, r = rows - 1; i < rows; i++, r--) {
            for (int j = 0, c = cols - 1; j < cols; j++, c--) {
                // swap values
                int temp = matrix[i][j];
                matrix[i][j] = matrix[r][c];
                matrix[r][c] = temp;

                counter++;
                if (counter > (rows * cols) / 2 - 1) {
                    return;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };

        System.out.println("matrix:");
        printMatrix(matrix);

        inverseMatrix(matrix);

        System.out.println("\ninverse matrix:");
        printMatrix(matrix);
    }
}



/*
run:

matrix:
   1   2   3   4
   5   6   7   8
   9  10  11  12

inverse matrix:
  12  11  10   9
   8   7   6   5
   4   3   2   1

*/

 

 



answered May 16, 2024 by avibootz
edited 1 day ago by avibootz
...