Go语言程序:数组元素旋转
在本教程中,我们将学习如何编写一个Go语言程序来旋转数组。我们将为此编写两个程序。一个用于向左旋转数组,另一个用于向右旋转数组。
算法
步骤1 − 导入fmt包,允许我们在屏幕上打印任何内容。
步骤2 − 创建一个名为rotateLeft()的函数,该函数在旋转后返回最终数组。
步骤3 − 此函数使用for循环迭代数组,并在每次迭代中调用rotateLeftByOne()函数。
步骤4 − 此函数以数组作为参数,并使用for循环迭代数组变量。
步骤5 − 在每次迭代中,我们将下一个值放在前一个位置,并恢复第一个元素。
步骤6 − 现在调用main()函数。
步骤7 − 初始化一个整数数组并为其赋值。
步骤8 − 在屏幕上打印数组,并通过将数组和元素应移动的次数作为参数传递给函数来调用rotateLeft()函数。
步骤9 − 使用fmt.Println()函数在屏幕上打印最终数组。
向左旋转数组
示例
以下代码演示了如何使用用户定义的函数向左旋转数组。
package main
import "fmt"
// making a function to rotate elements of array
func rotateLeft(arr []int, count int) {
for i := 0; i < count; i++ {
rotateLeftByOne(arr)
}
}
func rotateLeftByOne(arr []int) {
var i int = 0
var temp int = arr[0]
for ; i < len(arr)-1; i++ {
arr[i] = arr[i+1]
}
arr[i] = temp
}
func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 8}
fmt.Println("The entered array is:", arr)
rotateLeft(arr, 3)
fmt.Println("The array obtained by rotating it to left by 3 positions is:", arr)
}
输出
The entered array is: [1 2 3 4 5 6 7 8] The array obtained by rotating it to left by 3 positions is: [4 5 6 7 8 1 2 3]
向右旋转数组
示例
以下代码演示了一个Go语言程序,该程序可以将数组元素向右旋转任意次数。
package main
import "fmt"
func rotateRight(arr []int, count int) {
for i := 0; i < count; i++ {
var j, last int
length := len(arr)
last = arr[length-1]
for j = length - 1; j > 0; j-- {
arr[j] = arr[j-1]
}
arr[0] = last
}
}
func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 8}
fmt.Println("The entered array is:", arr)
rotateRight(arr, 3)
fmt.Println("The array obtained by rotating it to right by 3 positions is:", arr)
}
输出
The entered array is: [1 2 3 4 5 6 7 8] The array obtained by rotating it to right by 3 positions is: [6 7 8 1 2 3 4 5]
使用内部函数向右旋转数组
语法
func copy(dst, str[] type) int
GO语言中的copy函数用于将一个源数组的值复制到目标数组,并返回复制的元素数量作为结果。它以两个数组作为参数。
func make ([] type, size, capacity)
Go语言中的make函数用于创建数组/映射,它接受要创建的变量类型、其大小和容量作为参数。
示例
现在让我们来看另一个程序,我们可以使用它来使用内部函数将数组变量向右旋转。
package main
import "fmt"
func rotateRight(nums []int, k int) {
k %= len(nums)
new_array := make([]int, len(nums))
copy(new_array[:k], nums[len(nums)-k:])
copy(new_array[k:], nums[:len(nums)-k])
copy(nums, new_array)
}
func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 8}
fmt.Println("The entered array is:", arr)
rotateRight(arr, 4)
fmt.Println("The array obtained by rotating it to right by 4 positions is:", arr)
}
输出
The entered array is: [1 2 3 4 5 6 7 8] The array obtained by rotating it to right by 4 positions is: [5 6 7 8 1 2 3 4]
结论
我们已经成功编译并执行了一个Go语言程序,用于旋转数组的元素以及示例。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP