Golang 如何获得整数的随机换位
Go语言提供了内置支持,帮助生成指定类型的随机数,这一切都在math/rand包中实现。这个包实现了伪随机数生成器。这些随即数是由一个源生成的,每当程序运行时,该源都会生成一个确定的值序列。如果你需要做安全敏感的工作,那么请使用crypto/rand包。
你可以使用math/rand包提供的Perm()函数从默认源中生成包含n个int的切片,该切片包含在整数[0,n)的一个非负伪随机排列。因此,你需要使用import关键字在程序中添加math/rand包来访问Perm()函数。
语法:
func Perm(n int) []int
接下来我们用举例子的方式来讲解这个概念:
Example1:
// Golang program to illustrate
// how to get a random number
package main
import (
"fmt"
"math/rand"
)
// Main function
func main() {
// Getting the random permutation
// of integers in the form of slice
// Using Perm() function
for _, res_1 := range rand.Perm(4) {
// Displaying the result
fmt.Println("Slice 1 Element: ", res_1)
}
for _, res_2 := range rand.Perm(3) {
// Displaying the result
fmt.Println("Slice 2 Element: ", res_2)
}
}
输出:
Slice 1 Element: 0
Slice 1 Element: 1
Slice 1 Element: 2
Slice 1 Element: 3
Slice 2 Element: 1
Slice 2 Element: 2
Slice 2 Element: 0
Example2:
// Golang program to illustrate
// how to get a random permutation
// of integers
package main
import (
"fmt"
"math/rand"
)
// Main function
func main() {
// Getting the random permutation
// of integers in the form of slice
// Using Perm() function
res_1 := rand.Perm(5)
res_2 := rand.Perm(7)
fmt.Println("Slice 1: ", res_1)
// Finding the length of the slice
fmt.Println("Length of Slice 1: ", len(res_1))
// Finding the capacity of the slice
fmt.Println("Capacity of Slice 1: ", cap(res_1))
fmt.Println("Slice 2: ", res_2)
// Finding the length of the slice
fmt.Println("Length of Slice 2: ", len(res_2))
// Finding the capacity of the slice
fmt.Println("Capacity of Slice 2: ", cap(res_2))
}
输出:
Slice 1: [0 4 2 3 1]
Length of Slice 1: 5
Capacity of Slice 1: 5
Slice 2: [4 1 5 0 3 2 6]
Length of Slice 2: 7
Capacity of Slice 2: 7
极客教程