Tbalz
Tbalz

Reputation: 692

How to choose from a range of random numbers in Golang?

From my code below I can choose from a group of random numbers 0-4 when (5) is selected as the argument for Perm. However I would like to choose random numbers from a different range such as 6-10. How would I be able to do this please?

r := rand.New(rand.NewSource(time.Now().UnixNano()))
i := r.Perm(5)
fmt.Printf("%v\n", i)
fmt.Printf("%d\n", i[0])
fmt.Printf("%d\n", i[1])

Upvotes: 0

Views: 1826

Answers (2)

Jaybeecave
Jaybeecave

Reputation: 876

func RandomInt(min int, max int) int {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    p := r.Perm(max - min + 1)
    return p[min]
}

based on the answer @peterSO provided

Upvotes: 1

peterSO
peterSO

Reputation: 166616

For example,

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    min, max := 6, 10
    p := r.Perm(max - min + 1)
    fmt.Println(p)
    for i := range p {
        p[i] += min
    }
    fmt.Println(p)

    for _, r := range p {
        fmt.Println(r)
    }
}

Output:

[1 2 3 4 0]
[7 8 9 10 6]
7
8
9
10
6

Upvotes: 1

Related Questions