Averaging by time in a slice of structs

108 views
Skip to first unread message

Christian Espinoza

unread,
Sep 2, 2013, 10:31:37 AM9/2/13
to golan...@googlegroups.com
Hi guys, I'm averaging values by hour in a slice of structs in a basic way, and I would get a better aproach to it in order to get a most generic funcion that can also get averaging by hours, days, weeks, etc.


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
}

Thanks in advance.
Christian.

Kyle Lemons

unread,
Sep 2, 2013, 1:45:40 PM9/2/13
to Christian Espinoza, golang-nuts
Time math is frought with peril, but that being said I think this should be mostly correct:

I think it came out quite nicely.



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Nigel Tao

unread,
Sep 2, 2013, 7:39:34 PM9/2/13
to Christian Espinoza, golang-nuts
On Tue, Sep 3, 2013 at 12:31 AM, Christian Espinoza
<chesp...@gmail.com> wrote:
> Hi guys, I'm averaging values by hour in a slice of structs in a basic way,
> and I would get a better aproach to it in order to get a most generic
> funcion that can also get averaging by hours, days, weeks, etc.

I'd write it like http://play.golang.org/p/ytA-yw9iww

Christian Espinoza

unread,
Sep 3, 2013, 3:44:41 PM9/3/13
to golan...@googlegroups.com, Christian Espinoza
Thanks Kyle, I'm checking it..

Christian Espinoza

unread,
Sep 3, 2013, 3:45:26 PM9/3/13
to golan...@googlegroups.com, Christian Espinoza
Nice!, Thanks Nigel...
Reply all
Reply to author
Forward
0 new messages