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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to transpose a matrix (swap rows and columns) in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

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

    // allocate transposed matrix
    result := make([][]int, cols)
    for i := range result {
        result[i] = make([]int, rows)
    }

    // fill transposed values
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            result[j][i] = matrix[i][j]
        }
    }

    return result
}

func Print(matrix [][]int) {
    for _, row := range matrix {
        fmt.Println(row)
    }
}

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

    t := Transpose(matrix)
    Print(t)
}



/*
run:

[1 4 7]
[2 5 8]
[3 6 9]

*/

 



answered May 25 by avibootz
...