1 Star 0 Fork 1

常清静矣/golang-100

forked from 蓝桥云课/golang-100 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
042-splitSlice.go 646 Bytes
一键复制 编辑 原始数据 按行查看 历史
konroyliu 提交于 2021-03-22 16:37 . golang-100 answer
package main
import (
"errors"
"fmt"
)
func SplitSliceInChunks(a []int, chuckSize int) ([][]int, error) {
if chuckSize < 1 {
return nil, errors.New("chuckSize must be greater that zero")
}
chunks := make([][]int, 0, (len(a)+chuckSize-1)/chuckSize)
for chuckSize < len(a) {
a, chunks = a[chuckSize:], append(chunks, a[0:chuckSize:chuckSize])
}
chunks = append(chunks, a)
return chunks, nil
}
func main() {
a := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
chunks, err := SplitSliceInChunks(a, 4)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%v", chunks)
// Output:
// [[0 1 2 3] [4 5 6 7] [8 9]]
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/syongaaa/golang-100.git
git@gitee.com:syongaaa/golang-100.git
syongaaa
golang-100
golang-100
master

搜索帮助