Skip to content

Commit

Permalink
prevent negative weights in Choice
Browse files Browse the repository at this point in the history
These should break things (by design), so let's just guard against it at the API interface via type system.

Things are kept internally as ints because most golang stdlib functions expect that, so we can avoid casting everywhere.
  • Loading branch information
mroth committed Dec 11, 2018
1 parent def26bd commit 950f301
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
4 changes: 2 additions & 2 deletions weightedrand.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
// Choice is a generic wrapper that can be used to add weights for any object
type Choice struct {
Item interface{}
Weight int
Weight uint
}

// A Chooser caches many possible Choices in a structure designed to improve
Expand All @@ -38,7 +38,7 @@ func NewChooser(cs ...Choice) Chooser {
totals := make([]int, n, n)
runningTotal := 0
for i, c := range cs {
runningTotal += c.Weight
runningTotal += int(c.Weight)
totals[i] = runningTotal
}
return Chooser{data: cs, totals: totals, max: runningTotal}
Expand Down
8 changes: 4 additions & 4 deletions weightedrand_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func mockChoices(n int) []Choice {
for i := 0; i < n; i++ {
s := "⚽️"
w := rand.Intn(10)
c := Choice{Item: s, Weight: w}
c := Choice{Item: s, Weight: uint(w)}
choices = append(choices, c)
}
return choices
Expand All @@ -35,7 +35,7 @@ func TestWeightedChoice(t *testing.T) {
presorted data. */
list := rand.Perm(10)
for _, v := range list {
c := Choice{Weight: v, Item: v}
c := Choice{Weight: uint(v), Item: v}
choices = append(choices, c)
}
t.Log("FYI mocked choices of", choices)
Expand All @@ -59,8 +59,8 @@ func TestWeightedChoice(t *testing.T) {
for i, c := range choices[0 : len(choices)-1] {
next := choices[i+1]
cw, nw := c.Weight, next.Weight
if !(chosenCount[cw] < chosenCount[nw]) {
t.Error("Value not lesser", cw, nw, chosenCount[cw], chosenCount[nw])
if !(chosenCount[int(cw)] < chosenCount[int(nw)]) {
t.Error("Value not lesser", cw, nw, chosenCount[int(cw)], chosenCount[int(nw)])
}
}

Expand Down

0 comments on commit 950f301

Please sign in to comment.