From 6e1bfc177d67caf213a27c0ca561662c7bb6b9fb Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Fri, 24 Mar 2023 11:51:29 -0600 Subject: [PATCH] fix random weighted char because %sum can never get last value of sum --- src/device/input/random.go | 7 ++++++- src/device/input/random_test.go | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) 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 {