Skip to content

Instantly share code, notes, and snippets.

@cia-rana
Last active February 19, 2020 05:55
Show Gist options
  • Save cia-rana/6c43741f6db837c378f9cd9f701ee6cd to your computer and use it in GitHub Desktop.
Save cia-rana/6c43741f6db837c378f9cd9f701ee6cd to your computer and use it in GitHub Desktop.
[Go]重み付き乱択アルゴリズムを整数だけで完結させる ref: https://qiita.com/cia_rana/items/dca5b008fcee67adda50
weights := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
boundaries := make([]int, len(weights)+1)
for i := 1; i < len(boundaries); i++ {
boundaries[i] = boundaries[i-1] + weights[i-1]
}
x := rand.Intn(boundaryLast) + 1
idx := sort.SearchInts(boundaries, x)
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
const N = 1000000
func main() {
rand.Seed(time.Now().UnixNano())
weights := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
boundaries := make([]int, len(weights)+1)
for i := 1; i < len(boundaries); i++ {
boundaries[i] = boundaries[i-1] + weights[i-1]
}
boundaryLast := boundaries[len(boundaries)-1]
counter := make([]int, len(weights))
for i := 0; i < N; i++ {
x := rand.Intn(boundaryLast) + 1
idx := sort.SearchInts(boundaries, x) - 1
counter[idx]++
}
fmt.Println("|weight|expected|actual|")
fmt.Println("|:-:|:-:|:-:|")
for i := 0; i < len(weights); i++ {
fmt.Printf(
"|%d|%f|%f|\n",
weights[i],
float64(weights[i])/float64(boundaryLast),
float64(counter[i])/float64(N),
)
}
}
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
const N = 1000000
func main() {
rand.Seed(time.Now().UnixNano())
waits := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
boundaries := make([]int, len(waits)+1)
for i := 1; i < len(boundaries); i++ {
boundaries[i] = boundaries[i-1] + waits[i-1]
}
boundaryLast := boundaries[len(boundaries)-1]
counter := make([]int, len(waits))
for i := 0; i < N; i++ {
x := rand.Intn(boundaryLast)+1
idx := sort.SearchInts(boundaries, x) - 1
counter[idx]++
}
fmt.Println("|wait|expected|actual|")
fmt.Println("|:-:|:-:|:-:|")
for i := 0; i < len(waits); i++ {
fmt.Printf("|%d|%f|%f|\n", waits[i], float64(waits[i]) / float64(boundaryLast), float64(counter[i]) / float64(N))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment