简体   繁体   中英

Golang Split 2 dimensional array into multiple arrays of a single dimension

I have an array of two dimensions, how do I, out of that, make multiple arrays with a single dimension?

I need separate arrays as I need to pass an array with a single dimension to another function.

actions := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
batchSize := 3
batches := make([][]int, 0, (len(actions)+batchSize-1)/batchSize)

for batchSize < len(protoFiles) {
    actions, batches = actions[batchSize:], append(batches, actions[0:batchSize:batchSize])
}
batches = append(batches, actions)

how do I ... make multiple arrays with a single dimension?


For your example,

package main

import "fmt"

func batchActions(a []int, c int) [][]int {
    r := (len(a) + c - 1) / c
    b := make([][]int, r)
    lo, hi := 0, c
    for i := range b {
        if hi > len(a) {
            hi = len(a)
        }
        b[i] = a[lo:hi:hi]
        lo, hi = hi, hi+c
    }
    return b
}

func main() {
    actions := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println(actions)
    batchSize := 3
    batches := batchActions(actions, batchSize)
    fmt.Println(batchSize, batches)
}

Playground: https://play.golang.org/p/ETazZl1a-2F

Output:

[0 1 2 3 4 5 6 7 8 9]
3 [[0 1 2] [3 4 5] [6 7 8] [9]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM