Skip to content
This repository was archived by the owner on Aug 21, 2024. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions rand/random.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package rand

import (
"math/rand"
"sort"
"time"
)

type WeightedRandom struct {
rand *rand.Rand
choices []RandChoice
}

type RandChoice struct {
Chance float64
Value interface{}
}

func NewWeightedRandom(choices []RandChoice, seed int64) *WeightedRandom {
if seed == 0 {
seed = time.Hour.Nanoseconds()
}

sort.Slice(choices, func(i, j int) bool { return choices[i].Chance < choices[j].Chance })

return &WeightedRandom{
rand: rand.New(rand.NewSource(seed)),
choices: choices[:],
}
}

func (wr WeightedRandom) Get() interface{} {
var total float64
for _, v := range wr.choices {
total += v.Value.(float64)
}

rand := wr.rand.Float64() * total
for _, v := range wr.choices {
if v.Chance > rand {
return v.Value
}

rand -= v.Chance
}
return nil
}