Gists
This is a sample script for sorting a slice using Golang. Recently, I had a situation for sorting the coordinates of cells of Spreadsheet. As a test case, it thinks of the situation that the randomized cells are sorted. I think that this can be also used for a table except for Spreadsheet.
Sample slice:
The sample slice is as follows.
ar := []struct {
row int
col int
value string
}{
{0, 0, "A1"},
{0, 1, "B1"},
{0, 2, "C1"},
{1, 0, "A2"},
{1, 1, "B2"},
{1, 3, "D2"},
{2, 0, "A3"},
{2, 2, "C3"},
}
When each element of above slice is put to a Spreadsheet, it becomes as follows.
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