• 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
    }
  • 相关阅读:
    join()方法作用
    多线程的运行状态
    守护线程和非守护线程
    多线程快速入门
    Spring Boot2.0之注解方式启动Springmvc
    Spring Boot2.0之 原理—创建内置Tomcat容器
    Spring Boot2.0之纯手写框架
    Sprin Boot2.0之整合Mybatis整合分页插件
    linux下通过acl配置灵活目录文件权限(可用于ftp,web服务器的用户权限控制)
    PHP编程效率的20个要点
  • 原文地址:https://www.cnblogs.com/taotaozhuanyong/p/15498261.html
Copyright © 2020-2023  润新知