Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active May 7, 2024 07:51
Show Gist options
  • Save tanaikech/5cb41424ff8be0fdf19e78d375b6adb8 to your computer and use it in GitHub Desktop.
Save tanaikech/5cb41424ff8be0fdf19e78d375b6adb8 to your computer and use it in GitHub Desktop.
Transposing Slice From (n x m) To (m x n) for golang

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

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

@bubenkoff
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment