diff --git a/src/device/input/random.go b/src/device/input/random.go index c487002..3039054 100644 --- a/src/device/input/random.go +++ b/src/device/input/random.go @@ -6,6 +6,7 @@ import ( "io" "math/rand" "os" + "sort" "time" "github.com/go-yaml/yaml" @@ -87,11 +88,15 @@ func randomCharFromWeights(m map[byte]int) func() byte { } sum += v } + sort.Slice(result, func(i, j int) bool { + return result[i].i < result[j].i + }) if sum <= 0 { panic("weights must total nonzero") } return func() byte { - n := rand.Int() % sum + r := rand.Int() + n := r % (sum + 1) for _, v := range result { n -= v.i if n <= 0 { diff --git a/src/device/input/random_test.go b/src/device/input/random_test.go index df0812e..91feeeb 100644 --- a/src/device/input/random_test.go +++ b/src/device/input/random_test.go @@ -8,7 +8,7 @@ import ( func TestRandomCharFromWeights(t *testing.T) { weights := map[byte]int{ 'a': 1, - 'b': 99, + 'b': 20, } foo := randomCharFromWeights(weights) for {