to be
a problem slover

go split number into intervals

Split number into intervals, so that each go routine can concurrent process part of the job.

func ToIntervals(start int64, end int64, interval int64) (intervals [][2]int64, err error) {
    if start > end {
        return nil, errors.New(fmt.Sprintf("invalid input %d %d %d, start > end", start, end, interval))
    }
    if interval < 0 {
        return nil, errors.New(fmt.Sprintf("invalid input %d %d %d, interval <= 0", start, end, interval))
    }
    if interval == 0 || interval > end-start {
        return [][2]int64{{start, end}}, nil
    }
    for i := start; i <= end; i += interval {
        if i+interval-1 > end {
            intervals = append(intervals, [2]int64{i, end})
            break
        }
        intervals = append(intervals, [2]int64{i, i + interval - 1})
    }
    return intervals, nil
}

test

func TestToIntervals(t *testing.T) {
    intervals, err := ToIntervals(0, 10, 3)
    t.Log(intervals, err) // [[0 2] [3 5] [6 8] [9 10]]
}
赞(3) 打赏
欢迎转载,注明出处:刘世明的博客 » go split number into intervals

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下作者

支付宝扫一扫打赏

微信扫一扫打赏