Generating random numbers over a range in Go

前端 未结 5 2000
花落未央
花落未央 2021-01-07 16:27

All the integer functions in math/rand generate non-negative numbers.

rand.Int() int              // [0, MaxInt]
rand.Int31() int32          // [0, MaxInt32]         


        
相关标签:
5条回答
  • 2021-01-07 17:08

    A small utility I wrote for generating random slices(very much like python range)

    Code - https://github.com/alok87/goutils/blob/master/pkg/random/random.go

    import "github.com/alok87/goutils/pkg/random"
    random.RangeInt(2, 100, 5)
    
    [3, 10, 30, 56, 67]
    
    0 讨论(0)
  • 2021-01-07 17:11

    I found this example at Go Cookbook, which is equivalent to rand.Range(min, max int) (if that function existed):

    rand.Intn(max - min) + min
    
    0 讨论(0)
  • 2021-01-07 17:15

    As to prevent repeating min and max over and over again, I suggest to switch range and random in thinking about it. This is what I found to work as expected:

    package main
    
    import (
        "fmt"
        "math/rand"
    )
    
    // range specification, note that min <= max
    type IntRange struct {
        min, max int
    }
    
    // get next random value within the interval including min and max
    func (ir *IntRange) NextRandom(r* rand.Rand) int {
        return r.Intn(ir.max - ir.min +1) + ir.min
    }
    
    func main() {
        r := rand.New(rand.NewSource(55))
        ir := IntRange{-1,1}
        for i := 0; i<10; i++ {
            fmt.Println(ir.NextRandom(r))
        }
    }
    

    See on Go Playground

    Specifying the range

    The solution you found in the Cookbook misses to exactly specify how min and max work, but of course it meets your specification ([-min, max)). I decided to specify the range as a closed interval ([-min, max], that means its borders are included in the valid range). Compared to my understanding of the Cookbook description:

    gives you that random number within any two positive numbers that you specify (in this case, 1 and 6).

    (which can be found below the code snippet in the Golang Cookbook)

    the Cookbook implementation is off by one (which of course brings it in good company with lots of programs that are helpful at first glance).

    0 讨论(0)
  • 2021-01-07 17:17

    Solution that worked for me is: j = rand.Intn(600) - 100 where m is 100 and n is 500, it will generate numbers from -100 to 499.

    0 讨论(0)
  • 2021-01-07 17:29

    This will generate random numbers within given range [a, b]

    rand.Seed(time.Now().UnixNano())
    n := a + rand.Intn(b-a+1)
    

    source

    0 讨论(0)
提交回复
热议问题