How to mirror a matrix across the main diagonal in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"log"
)

func mirrorMatrix(matrix [][]int) ([][]int, error) {
	// Validate input: Ensure the matrix is not empty
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return nil, fmt.Errorf("matrix cannot be empty")
	}

	// Get the dimensions of the matrix
	rows := len(matrix)
	cols := len(matrix[0])

	// Create a new matrix with mirror dimensions
	mirror := make([][]int, cols)
	for i := range mirror {
		mirror[i] = make([]int, rows)
	}

	// Perform the mirror operation
	for i := 0; i < rows; i++ {
		for j := 0; j < cols; j++ {
			mirror[j][i] = matrix[i][j]
		}
	}

	return mirror, nil
}

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

	fmt.Println("Original Matrix:")
	for _, row := range matrix {
		fmt.Println(row)
	}

	// Mirror the matrix
	mirror, err := mirrorMatrix(matrix)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	fmt.Println("\nMirrored Matrix:")
	for _, row := range mirror {
		fmt.Println(row)
	}
}



/*
run:

Original Matrix:
[1 2 3]
[4 5 6]
[7 8 9]

Mirrored Matrix:
[1 4 7]
[2 5 8]
[3 6 9]

*/

 



answered Aug 28 by avibootz
...