Mercurial > gemma
changeset 4365:e739a4806d7c
rounding to full days: Fixed typos. Make golint happy with the comments. Unexport local type. Simplify and tightend code.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Mon, 09 Sep 2019 18:07:10 +0200 |
parents | 496bbf0f618c |
children | 81dc260b38aa |
files | pkg/common/round.go |
diffstat | 1 files changed, 19 insertions(+), 20 deletions(-) [+] |
line wrap: on
line diff
--- a/pkg/common/round.go Mon Sep 09 17:39:57 2019 +0200 +++ b/pkg/common/round.go Mon Sep 09 18:07:10 2019 +0200 @@ -19,49 +19,48 @@ "time" ) -type Rest struct { - Key int - Rest float64 -} +// SumPreservingRound rounds the values of arr preserving the sum. +func SumPreservingRound(arr []float64) []int { -// Simple sum preserving rounding method: -func SumPreservingRound(arr []float64) []int { + type rest struct { + key int + rest float64 + } + var ( - sum float64 - rests []Rest + result = make([]int, len(arr)) + rests = make([]rest, len(arr)) + sum float64 + newSum int ) - result := make([]int, len(arr)) // floor all values for i, v := range arr { sum += v result[i] = int(v) - rests = append(rests, Rest{Key: i, Rest: v - float64(result[i])}) + newSum += int(v) + rests[i] = rest{key: i, rest: v - float64(result[i])} } - // find the difference in summs - var newSum int - for _, v := range result { - newSum += v - } - delta := int(math.Round(sum)) - newSum - // spread delta over values with highest rest sort.Slice(rests, func(i, j int) bool { - return rests[i].Rest > rests[j].Rest + return rests[i].rest > rests[j].rest }) + + // find the difference in sums + delta := int(math.Round(sum)) - newSum for _, v := range rests { if delta <= 0 { break } - result[v.Key]++ + result[v.key]++ delta-- } return result } -// Round anarray of Duratons to full days +// RoundToFullDays rounds durations to full days. func RoundToFullDays(durations []time.Duration) []int { days := make([]float64, len(durations)) for i, v := range durations {