Saturday, September 16, 2017

Slice chunking in Go

Slice chunking in Go

package main

import "fmt"

var (
 logs   = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}
 numCPU = 3
)

func main() {

 var divided [][]string

 chunkSize := (len(logs) + numCPU - 1) / numCPU

 for i := 0; i < len(logs); i += chunkSize {
  end := i + chunkSize

  if end > len(logs) {
   end = len(logs)
  }

  divided = append(divided, logs[i:end])
 }

 fmt.Printf("%#v\n", divided)
}

Reference:

https://stackoverflow.com/questions/35179656/slice-chunking-in-go

No comments: