Matrix Transpose With Slices
Rebuild a matrix with rows and columns exchanged through nested loops over a fresh [][]int, keeping the source untouched for shape-aware transformations.
Code
package main
import "fmt"
// transpose swaps rows and columns into a fresh slice of slices
func transpose(matrix [][]int) [][]int {
rows, cols := len(matrix), len(matrix[0])
out := make([][]int, cols)
for c := 0; c < cols; c++ {
out[c] = make([]int, rows)
for r := 0; r < rows; r++ {
out[c][r] = matrix[r][c]
}
}
return out
}
func main() {
grid := [][]int{{1, 2, 3}, {4, 5, 6}}
for _, row := range transpose(grid) {
fmt.Println(row)
}
fmt.Println(transpose([][]int{{7}}))
}Matrix Transpose With Slices: what runs and why
Matrix Transpose With Slices is built around the functions transpose and main.
for c := 0; c < cols; c++ is the per-item workhorse.
Points of care
- No package manager enters the picture — each call lands on a built-in.
Putting it to use
Signature: func transpose(matrix [][]int) [][]int
main calls 1 helper in sequence: transpose.
Core lines
func transpose(matrix [][]int) [][]int {
rows, cols := len(matrix), len(matrix[0])
out := make([][]int, cols)
for c := 0; c < cols; c++ {
out[c] = make([]int, rows)
for r := 0; r < rows; r++ {
out[c][r] = matrix[r][c]
}
}
return out
}
for _, row := range transpose(grid) {
fmt.Println(row)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Matrix Transpose With Slices?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.