英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论