Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make IntRange explicitly inclusive to [min, max]. #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
26 changes: 11 additions & 15 deletions randutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,19 @@ const (

var MinMaxError = errors.New("Min cannot be greater than max.")

// IntRange returns a random integer in the range from min to max.
// IntRange returns a random integer in the range from min to max inclusive.
func IntRange(min, max int) (int, error) {
var result int
switch {
case min > max:
if min > max {
// Fail with error
return result, MinMaxError
case max == min:
result = max
case max > min:
maxRand := max - min
b, err := rand.Int(rand.Reader, big.NewInt(int64(maxRand)))
if err != nil {
return result, err
}
result = min + int(b.Int64())
}
maxRand := max - min + 1
b, err := rand.Int(rand.Reader, big.NewInt(int64(maxRand)))
if err != nil {
return result, err
}
result = min + int(b.Int64())
return result, nil
}

Expand Down Expand Up @@ -92,7 +88,7 @@ func AlphaString(n int) (string, error) {
func ChoiceString(choices []string) (string, error) {
var winner string
length := len(choices)
i, err := IntRange(0, length)
i, err := IntRange(0, length - 1)
winner = choices[i]
return winner, err
}
Expand All @@ -101,7 +97,7 @@ func ChoiceString(choices []string) (string, error) {
func ChoiceInt(choices []int) (int, error) {
var winner int
length := len(choices)
i, err := IntRange(0, length)
i, err := IntRange(0, length - 1)
winner = choices[i]
return winner, err
}
Expand All @@ -126,7 +122,7 @@ func WeightedChoice(choices []Choice) (Choice, error) {
for _, c := range choices {
sum += c.Weight
}
r, err := IntRange(0, sum)
r, err := IntRange(0, sum - 1)
if err != nil {
return ret, err
}
Expand Down