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

huangapple go评论76阅读模式
英文:

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

问题

从下面的代码中,当将参数 Perm 设置为 5 时,我可以从一组随机数 0-4 中选择。然而,我想从不同的范围(例如 6-10)中选择随机数。请问我该如何做到这一点呢?

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])

请提供翻译后的代码。

英文:

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])

答案1

得分: 1

例如,

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)
    }
}

输出:

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

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

答案2

得分: 1

根据 @peterSO 提供的答案:

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

根据 @peterSO 提供的答案编写的代码。

英文:
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

huangapple
  • 本文由 发表于 2016年2月12日 12:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/35354800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定