Go语言程序:旋转切片元素
切片与数组类似,都是元素序列。但数组是固定长度的元素序列,而切片是动态数组,其大小可以改变。切片比数组更高效、速度更快,并且它们是按引用传递而不是按值传递。这里我们将学习使用Go语言旋转切片元素的各种技巧。
语法
func append(slice, element_1, element_2…, element_N) []T
`append`函数用于向数组切片添加值。它接受多个参数。第一个参数是要添加值的数组,后跟要添加的值。然后,该函数返回包含所有值的最终数组切片。
func append(slice, element_1, element_2…, element_N) []T
`append`函数用于向数组切片添加值。它接受多个参数。第一个参数是要添加值的数组,后跟要添加的值。然后,该函数返回包含所有值的最终数组切片。
func copy(dst, str[] type) int
Go语言中的`copy`函数用于将一个源数组的值复制到目标数组,并返回复制的元素数量作为结果。它以两个数组作为参数。
func make ([] type, size, capacity)
Go语言中的`make`函数用于创建数组/映射,它接受要创建的变量类型、大小和容量作为参数。
算法
步骤1 - 创建一个`main`包,并在程序中声明`fmt`(格式化包),其中`main`产生可执行代码,`fmt`帮助格式化输入和输出。
步骤2 - 创建一个`main`函数,在该函数中创建一个切片,并使用`append`函数向其中添加元素。
步骤3 - 使用Go语言中的`print`语句在控制台上打印切片。
步骤4 - 从`main`函数中调用`rotate`函数,传入两个参数:要旋转的切片和旋转的位数。
步骤5 - 在`rotate`函数中,每次调用`reverse`函数时,一次向左,一次向右,最后是整个切片。
步骤6 - 在`reverse`函数中,使用Go语言的多重循环特性反转元素,切片中的值在特定位置反转。
步骤7 - 切片旋转后,使用`fmt.Println()`函数在控制台上打印它,其中`ln`表示换行。
示例1
在这个例子中,我们将学习如何通过在不同位置反转切片然后反转整个切片来旋转切片。
package main
import (
"fmt"
)
func rotate(slice []int, positions int) {
positions = positions % len(slice) //find the position
reverse(slice[:positions]) //reverse the beginning elements
reverse(slice[positions:]) //reverse the end elements
reverse(slice) //reverse the entire slice
}
func reverse(slice []int) {
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
slice[i], slice[j] = slice[j], slice[i]
}
}
func main() {
var slice []int // initialize slice
slice = append(slice, 10) //fill the slice using append function
slice = append(slice, 20)
slice = append(slice, 30)
slice = append(slice, 40)
slice = append(slice, 50)
fmt.Println("The original slice created here is: ", slice)
rotate(slice, 2) //call the rotate function
fmt.Println("The rotated slice is: ", slice)
}
输出
The original slice created here is: [10 20 30 40 50] The rotated slice is: [30 40 50 10 20]
示例2
在这个例子中,我们将学习如何使用内置的`copy`函数旋转切片。在`rotate`函数中,将通过创建另一个临时变量来复制值。让我们看看算法和代码是如何实现的。
package main
import (
"fmt"
)
func rotate(slice []int, position int) {
position = position % len(slice) //find position
temp := make([]int, position) //create a temp slice to store values
copy(temp, slice[:position])
copy(slice, slice[position:])
copy(slice[len(slice)-position:], temp) //copy elements from temp to end of slice
}
func main() {
var slice []int // initialize slice
slice = append(slice, 10) //fill the slice using append function
slice = append(slice, 20)
slice = append(slice, 30)
slice = append(slice, 40)
slice = append(slice, 50)
fmt.Println("The original slice created here is: ", slice)
rotate(slice, 2)
fmt.Println("The rotated slice is: ", slice) //print rotated slice
}
输出
The original slice created here is: [10 20 30 40 50] The rotated slice is: [30 40 50 10 20]
结论
我们使用两个示例执行了旋转切片的程序。在第一个示例中,我们使用`reverse`函数旋转切片;在第二个示例中,我们使用`copy`函数和一个额外的临时变量。因此,程序成功执行。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP