Golang对数组进行平分

背景:线上的接口处bug,测试很着急的找到我。当然,这个bug 并不是我写出来的,而是经历过日积月累,之前的开发人员,也没有关注过这个问题,出现在类似bug 也是在所难免的。

话不多说,这个问题刚好需要数组的平分可以搞定。代码如下:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    source := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}
    pageSize := 10
    pageSizee := 4
    fmt.Printf("%+v
", splitArray(source, IntToInt64(splitArrayCnt(len(source), pageSize)), int64(pageSize)))
    fmt.Printf("%+v
", splitArray(source, IntToInt64(splitArrayCnt(len(source), pageSizee)), int64(pageSizee)))

    res := splitArray(source, IntToInt64(splitArrayCnt(len(source), pageSize)), int64(pageSize))
    fmt.Println(len(res))
    for _, re := range res {
        fmt.Println(re)
    }
}

// sources源数组,num拆分份数,size每份的大小
func splitArray(sources []int64, num, pageSize int64) [][]int64 {
    max := int64(len(sources))
    if max < num {
        return nil
    }
    var segmens = make([][]int64, 0)
    quantity := pageSize
    end := int64(0)
    for i := int64(1); i <= num; i++ {
        qu := i * quantity
        if i != num {
            segmens = append(segmens, sources[i-1+end:qu])
        } else {
            segmens = append(segmens, sources[i-1+end:])
        }
        end = qu - i
    }
    return segmens
}

// sourceslen源数组长度,pageSize页数据量
// 获取拆分份数
func splitArrayCnt(sourceslen, pageSize int) int {
    if sourceslen < pageSize {
        return 1
    }
    s := sourceslen / pageSize
    y := sourceslen % pageSize
    if y > 0 {
        return s + 1
    } else {
        return s
    }
}

//IntToInt64 int 转int64
func IntToInt64(i int) int64 {
    i64, _ := strconv.ParseInt(strconv.Itoa(i), 10, 64)
    return i64
}
原文地址:https://www.cnblogs.com/taotaozhuanyong/p/15498261.html