Last active
September 22, 2018 02:54
-
-
Save artiya4u/61bb060796b10e7b76b2a95751220bca to your computer and use it in GitHub Desktop.
Demo algorithm to get the random choice with different weight.
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" | |
) | |
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