Skip to content

Instantly share code, notes, and snippets.

@artiya4u
Last active September 22, 2018 02:54
Show Gist options
  • Save artiya4u/61bb060796b10e7b76b2a95751220bca to your computer and use it in GitHub Desktop.
Save artiya4u/61bb060796b10e7b76b2a95751220bca to your computer and use it in GitHub Desktop.
Demo algorithm to get the random choice with different weight.
package main
import (
"fmt"
"math/rand"
)
func randomWithWeight(weights []int) int {
var sum int
for _, v := range weights {
sum += v
}
rnd := rand.Intn(sum)
for i := 0; i < len(weights); i++ {
if rnd < weights[i] {
return i
}
rnd -= weights[i]
}
return 0
}
func main() {
rand.Seed(64168918564)
// 4 Choice
weightOfChoice := []int{59, 1, 10, 30}
var freqs [4]int
// Loop 10,000 times
for i := 0; i < 100000; i++ {
freqs[randomWithWeight(weightOfChoice)] += 1
}
// Show the frequency of each choice.
for _, v := range freqs {
fmt.Println(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment