Skip to content

Instantly share code, notes, and snippets.

@catatsuy
Created October 14, 2015 11:08
Show Gist options
  • Save catatsuy/30213aee2dee489e7ac3 to your computer and use it in GitHub Desktop.
Save catatsuy/30213aee2dee489e7ac3 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"time"
)
type weight struct {
weight float64
threshold float64
count int
}
func main() {
lists := []*weight{&weight{weight: 1.0}, &weight{weight: 3.0}, &weight{weight: 5.0}, &weight{weight: 1.0}}
totalW := 0.0
for _, v := range lists {
(*v).threshold = totalW
totalW += v.weight
}
rand.Seed(time.Now().UnixNano())
for n := 0; n < 100000000; n++ {
rTotalW := rand.Float64() * totalW
for i := len(lists) - 1; i >= 0; i-- {
if lists[i].threshold <= rTotalW {
lists[i].count++
break
}
}
}
for k, v := range lists {
fmt.Printf("%d: %.2f %d\n", k, v.weight, v.count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment