我以基本方式在一片结构中按小时对值进行平均,我会得到更好的方法以获得最通用的函数,可以按小时、天、周等进行平均。在此先感谢大家。
package main
import (
"fmt"
"math/rand"
"time"
)
type Acc struct {
name string
money int
date time.Time
}
type Accs []Acc
const Tformat = "02/01/2006 15:04:05"
func main() {
var myaccs Accs
acc := 0
var loops int
var hour int
f1, _ := time.Parse(Tformat, "29/08/2013 00:00:19")
// Creating a Slice of structs
for i := 0; i < 10; i++ {
f1 = f1.Add(20 * time.Minute) //adding 20 minutes to every record
myaccs = append(myaccs, Acc{name: "christian", money: rand.Intn(200), date: f1})
fmt.Printf("Added to slice: %v, %d, %s\n", myaccs[i].name, myaccs[i].money, myaccs[i].date)
}
// Averaging
for _, v := range myaccs {
if acc == 0 {
hour = v.date.Hour()
acc += v.money
loops++
} else {
if v.date.Hour() == hour {
acc += v.money
loops++
} else {
fmt.Printf("Average money value to hour %d : %d\n", hour, acc / loops) //->Action
acc = v.money
hour = v.date.Hour()
loops = 1
}
}
//fmt.Println(v, acc, loops, hour)
}
fmt.Printf("Average money value to hour %d : %d\n", hour, acc / loops)//->Action
}
注意:Money 变量是一个 int,仅作为示例..
注2:我正在考虑数据已经排序
Playground :
http://play.golang.org/p/lL3YDD4ecE
最佳答案
时间数学充满了危险,但是 here是解决问题的一种方法:
type Snapshot struct {
Value AccountValue
At time.Time
}
type Granularity struct {
Name string
DateIncrement [3]int
DurIncrement time.Duration
DateFormat string
}
type Graph struct {
Granularity
Values map[string][]AccountValue
}
func (g *Graph) Add(snaps []Snapshot) {
if g.Values == nil {
g.Values = map[string][]AccountValue{}
}
for _, s := range snaps {
key := g.Format(s.At)
g.Values[key] = append(g.Values[key], s.Value)
}
}
func (g *Graph) Get(from, to time.Time) (snaps []Snapshot) {
from, to = g.Truncate(from), g.Truncate(to)
for cur := from; !to.Before(cur); cur = g.AddTo(cur) {
var avg, denom AccountValue
for _, v := range g.Values[g.Format(cur)] {
avg += v
denom += 1
}
if denom > 0 {
avg /= denom
}
snaps = append(snaps, Snapshot{
Value: avg,
At: cur,
})
}
return snaps
}
完整代码在 Playground 中
关于go - 使用 Go 在一片结构中按时间平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18575358/