func main() {
	data := []string{"a", "b", "c"}
	weights := []float64{0.6, 0.3, 0.1}
	results := map[string]int{"a": 0, "b": 0, "c": 0}
	runs := 1000

	fmt.Printf("%v => %v\n", data, weights)

	rand.Seed()
	for i := 0; i < runs; i++ {
		index := rand.WeightedChoice(weights, rand.Sum(weights))
		results[data[index]]++
	}

	for k, v := range results {
		fmt.Printf("%v => %v\n", k, float64(v)/float64(runs))
	}
}
Exemple #2
0
// selectString chooses a string based on the weight.
func selectString(dict map[string]int) string {
	rand.Seed()

	data := []string{}
	weights := []float64{}
	sum := 0.0

	for _, w := range dict {
		sum += float64(w)
	}

	for c, w := range dict {
		data = append(data, c)
		weights = append(weights, float64(w)/sum)
	}
	index := rand.WeightedChoice(weights, sum)
	result := data[index]

	return result
}