Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,788 questions

51,694 answers

573 users

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, 2025 by avibootz
...