Skip to content

Commit

Permalink
Update rand/rand.go
Browse files Browse the repository at this point in the history
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Kashif Khan <[email protected]>
  • Loading branch information
kashifkhan0771 and coderabbitai[bot] authored Nov 1, 2024
1 parent c12c656 commit dd9280d
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions rand/rand.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,20 @@ func NumberInRange(min, max int64) (int64, error) {
}

rangeSize := max - min + 1
// Calculate the largest multiple of rangeSize that fits in MaxInt64
limit := math.MaxInt64 - (math.MaxInt64 % rangeSize)

// Generate random number within the range
n, err := rand.Int(rand.Reader, big.NewInt(rangeSize))
if err != nil {
return 0, fmt.Errorf("failed to generate random number in range: %w", err)
for {
n, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
return 0, fmt.Errorf("failed to generate random number in range: %w", err)
}

if n.Int64() < limit {
return min + (n.Int64() % rangeSize), nil
}
// If we're above the limit, try again to ensure uniform distribution
}

return n.Int64() + min, nil
}

// String generates a random string using the both default cons
Expand Down

0 comments on commit dd9280d

Please sign in to comment.