Skip to content

Instantly share code, notes, and snippets.

@chespinoza
Created September 2, 2013 13:48
Show Gist options
  • Save chespinoza/6413050 to your computer and use it in GitHub Desktop.
Save chespinoza/6413050 to your computer and use it in GitHub Desktop.
Approach to get Average values by hour in a slice of structs with Golang
package main
import (
"fmt"
"math/rand"
"time"
)
type Acc struct {
name string
money int
fecha 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")
for i := 0; i < 10; i++ { // Creamos un slice de structuras para simulacion
f1 = f1.Add(20 * time.Minute) //suma 20 minutos
myaccs = append(myaccs, Acc{name: "christian", money: rand.Intn(200), fecha: f1})
fmt.Printf("Added: %v, %d, %s\n", myaccs[i].name, myaccs[i].money, myaccs[i].fecha)
}
// Tratar de promediar x hora
for _, v := range myaccs {
if acc == 0 {
hour = v.fecha.Hour()
acc += v.money
loops++
} else {
if v.fecha.Hour() == hour {
acc += v.money
loops++
} else {
fmt.Println(acc / loops) //->Action
acc = v.money
hour = v.fecha.Hour()
loops = 1
}
}
fmt.Println(v, acc, loops, hour)
}
fmt.Println(acc / loops) //->Action
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment