Golang 用于对数组元素进行洗牌
数组是一系列元素的固定序列,其中元素被放置在连续的内存位置上。我们将对数组的元素进行洗牌并随机放置。在第一种情况下,我们将使用费舍尔 – 耶茨洗牌算法。让我们看看如何使用不同的逻辑在Golang代码中执行它。
语法
rand.Seed(value)
Rand.Seed() 函数用于生成随机数。它以用户输入作为参数,该参数是生成随机数的上限。
func Now() Time
Now() 函数在time包中定义。该函数生成当前的本地时间。要使用该函数,我们首先需要在程序中导入time包。
func (t Time) UnixNano() int64
UnixNano()函数是在time包中定义的。该函数用于获取从UTC的1970年1月1日开始的秒数。它返回的最终结果是64位整数类型。
rand.Intn(n)
Intn() 函数定义在math/rand包中。它用于在[0, n]区间生成一个随机数,其中n是用户提供的数。如果提供的数小于0,该函数会抛出一个错误。
步骤
- 步骤1 - 创建一个main包并声明fmt(format包)、time和math/rand包。
-
步骤2 - 在main函数中创建一个数组。
-
步骤3 - 使用内部/用户定义的函数创建随机数。
-
步骤4 - 使用用户定义的函数开始洗牌过程。
-
步骤5 - 打印洗牌后数组的输出。
示例1
在这个示例中,我们将学习如何使用Fisher Yates Shuffle算法来洗牌数组的元素。
package main
import (
"fmt"
"math/rand" //import fmt and math/rand
)
//create main function to execute the program
func main() {
array := []int{10, 20, 30, 40, 50, 60, 70, 80} //create an array which is to shuffled
fmt.Println("The elements of array are:", array)
shuffle(array) //call the function shuffle
fmt.Println("The shuffled array given here is:")
fmt.Println(array)
}
// shuffle shuffles the elements of an array in place
func shuffle(array []int) {
for i := range array { //run the loop till the range of array
j := rand.Intn(i + 1) //choose any random number
array[i], array[j] = array[j], array[i] //swap the random element with current element
}
}
输出
The elements of array are: [10 20 30 40 50 60 70 80]
The shuffled array given here is:
[60 50 30 70 80 10 40 20]
示例2
在这个示例中,我们将使用rand.Seed函数来打乱数组的元素。
package main
import (
"fmt"
"math/rand" //import fmt, math/rand and time
"time"
)
//create main function to execute the program
func main() {
array := []int{10, 20, 30, 40, 50, 60} //create an array which is to shuffled
fmt.Println("The elements of array are:", array)
rand.Seed(time.Now().UnixNano()) // generate random numbers using this function
shuffle(array)
fmt.Println("The shuffled array is:")
fmt.Println(array)
}
func shuffle(array []int) {
for i := len(array) - 1; i > 0; i-- { //run the loop from the end till the start
j := rand.Intn(i + 1)
array[i], array[j] = array[j], array[i] //swap the random element with the current element
}
}
输出
The elements of array are: [10 20 30 40 50 60]
The shuffled array is:
[10 30 60 50 20 40]
结论
我们使用了两个示例的方法来执行对数组进行洗牌的程序。在第一个示例中,我们使用了Fisher Yates算法,而在第二个示例中,我们使用了rand.Seed函数。我们使用了不同的逻辑来洗牌数组。因此,程序成功执行。