package main
import (
"errors"
"fmt"
)
func main() {
fmt.Println(ChunkSlicesGroup(7, false, []int{1, 2, 3, 4}, []int{1, 22, 31, 42}, []int{55, 66})) //[[1 2 3 4 1 22 31] [42 55 66]] <nil>
fmt.Println(ChunkSlicesGroup(7, true, []int{1, 2, 3, 4}, []int{1, 22, 31, 42}, []int{55, 66})) //[[1 2 3 4 22 31 42] [55 66]] <nil>
}
// ChunkSlicesGroup 多个切片合并后按照指定长度进行切割分组
// Size 每个被分割的切片组长度
// IsDeduplication 是否需要去重切片元素
// Slices 需要处理的切片
func ChunkSlicesGroup[T comparable](Size int, IsDeduplication bool, Slices ...[]T) ([][]T, error) {
if Size <= 0 {
return nil, errors.New("size is Zero")
}
uniqueElements := make([]T, 0)
if IsDeduplication {
deduplicationMap := make(map[T]struct{})
for _, slices := range Slices {
for _, element := range slices {
if _, exists := deduplicationMap[element]; !exists {
deduplicationMap[element] = struct{}{}
uniqueElements = append(uniqueElements, element)
}
}
}
} else {
for _, slices := range Slices {
for _, element := range slices {
uniqueElements = append(uniqueElements, element)
}
}
}
uniqueElementsLen := len(uniqueElements)
slicesGroup := make([][]T, 0, (uniqueElementsLen+Size-1)/Size)
for i := 0; i < uniqueElementsLen; i += Size {
end := i + Size
if end > uniqueElementsLen {
end = uniqueElementsLen
}
slicesGroup = append(slicesGroup, uniqueElements[i:end])
}
return slicesGroup, nil
}
golang多个切片合并后按照指定长度进行切割分组
于 2024-05-14 11:37:34 首次发布