Created
October 14, 2015 11:08
-
-
Save catatsuy/30213aee2dee489e7ac3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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