Go语言程序:数组元素洗牌


数组是元素的固定序列,其中元素放置在连续的内存位置。我们将对数组的元素进行洗牌并随机放置。在第一种情况下,我们将使用Fisher-Yates洗牌算法。让我们看看如何使用Go语言代码中不同的逻辑来执行它。

语法

rand.Seed(value)

Rand.Seed()函数用于生成随机数。它接受用户输入作为参数,该参数是生成随机数的上限。

func Now() Time

Now()函数定义在time包中。此函数生成当前本地时间。要使用此函数,我们必须首先在程序中导入time包。

func (t Time) UnixNano() int64

UnixNano()函数定义在time包中。此函数用于获取自1970年1月1日UTC以来经过的秒数。它返回的最终结果是64位的整数类型。

rand.Intn(n)

Intn()函数定义在math/rand包中。它用于生成区间[0, n]内的随机数,其中n是用户提供的数字。如果提供的数字小于0,则该函数会抛出错误。

算法

  • 步骤1 - 创建一个package main并声明fmt(格式化包)、time和math/rand包

  • 步骤2 - 在main函数中创建一个数组

  • 步骤3 - 使用内部/用户定义的函数来创建随机数

  • 步骤4 - 使用用户定义的函数开始洗牌过程。

  • 步骤5 - 打印洗牌后数组的输出

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例1

在这个例子中,我们将学习如何使用Fisher-Yates洗牌算法来洗牌数组的元素。

Open Compiler
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函数来洗牌数组的元素。

Open Compiler
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函数。我们使用不同的逻辑对数组进行了洗牌。因此,程序成功执行。

更新于:2023年2月13日

852 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告