How to inverse N x M matrix in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func printMatrix(matrix [][]int) {
    rows := len(matrix)
    cols := len(matrix[0])

    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            // Pad each number to width 4
            fmt.Printf("%4d", matrix[i][j])
        }
        fmt.Println()
    }
}

func inverseMatrix(matrix [][]int) {
    rows := len(matrix)
    cols := len(matrix[0])
    counter := 0

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

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

func main() {
    matrix := [][]int{
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
    }

    fmt.Println("matrix:")
    printMatrix(matrix)

    inverseMatrix(matrix)

    fmt.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 1 day ago by avibootz
...