Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

go - joining 2 dimensional array by columns

I have 2 dimensional array on golang something like

array which contains [1,2,3,4]
                     [2,3,4,5]
                     [3,4,5,6]

and I want to join the array columns i.e the result should be

1,2,3
2,3,4
3,4,5
4,5,6

my approach is something like this to create 4 arrays and do something like this:

a := []int{}


for _, row := range array {
append (a,array[1])
append (b,array[2])
append (c,array[2])
append (d,array[2])


}

and then join those arrays something like this

fmt.Println(strings.Join(a[:], ","))
fmt.Println(strings.Join(b[:], ","))
fmt.Println(strings.Join(c[:], ","))
fmt.Println(strings.Join(d[:], ","))

my question if there are an option to access the array by columns not by row or if there are more usful way to do this?

question from:https://stackoverflow.com/questions/66054903/joining-2-dimensional-array-by-columns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of instantiating multiple arrays, you can just work with another two-dimensional array.

Here's a quick pass at an implementation (it could use more error checking, e.g. assumes all of the inner arrays in the input are the same length):

package main

import (
    "fmt"
)

func transpose(input [][]int) [][]int {
    result := make([][]int, len(input[0]))
    for _, row := range(input) {
        for j, value := range(row) {
            result[j] = append(result[j], value)
        }
    }
    return result
}

func main() {
    input := [][]int{{1,2,3,4}, {2,3,4,5}, {3,4,5,6}}
    result := transpose(input)
    
    fmt.Println(input)
    fmt.Println(result)
}

Output:

[[1 2 3 4] [2 3 4 5] [3 4 5 6]]
[[1 2 3] [2 3 4] [3 4 5] [4 5 6]]

Go Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...