-1

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)
deef0000dragon1
  • 357
  • 4
  • 17
  • 1
    First you have slices, not arrays. I don't understand what the code is supposed to do, the for loop condition never changes and you never break from the loop. Did you simply mean `for batchSize < len(actions)`? – JimB Feb 06 '20 at 14:35
  • 2
    The question as it stands is not very clear. You should add an example input, and the output that you would then expect. – deef0000dragon1 Feb 06 '20 at 14:52
  • Go does not have first-class multi-dimensional slices. You have a slice of slices. So `batches` is a single-dimensional slice, where each element is a single-dimensional slice. You can index into `batches` to get single-dimensional slices out of it. – Adrian Feb 06 '20 at 16:22

1 Answers1

1

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]]
peterSO
  • 158,998
  • 31
  • 281
  • 276