Transposing Slice From (n x m) To (m x n) for golang

Gists

This is a sample script for transposing slice from (n x m) to (m x n) for golang.

Script :

package main

import "fmt"

func transpose(slice [][]string) [][]string {
    xl := len(slice[0])
    yl := len(slice)
    result := make([][]string, xl)
    for i := range result {
        result[i] = make([]string, yl)
    }
    for i := 0; i < xl; i++ {
        for j := 0; j < yl; j++ {
            result[i][j] = slice[j][i]
        }
    }
    return result
}

func main() {
    sample := [][]string{
        []string{"a1", "a2", "a3", "a4", "a5"},
        []string{"b1", "b2", "b3", "b4", "b5"},
        []string{"c1", "c2", "c3", "c4", "c5"},
    }
    ar := transpose(sample)
    fmt.Println(ar)
}

Result :

[
    ["a1", "b1", "c1"],
    ["a2", "b2", "c2"],
    ["a3", "b3", "c3"],
    ["a4", "b4", "c4"],
    ["a5", "b5", "c5"]
]

The Go Playground

https://play.golang.org/p/XoZy7m65rEG

 Share!