所以我正在尝试编写一个方法,该方法需要两个切片,翻转两个切片,然后将它们相互提供。
前任。
s1 = {1,2,3,4,5}
s2 = {6,7,8,9,10}
应返回:
s1 = {10,9,8,7,6}
s2 = {5,4,3,2,1}
这是我的代码:
package main
import(
"fmt"
)
func main(){
f:= [5]int{1,2,3,4,5}
h:= [5]int{6,7,8,9,10}
var sliceF []int = f[0:5]
var sliceH []int = h[0:5]
fmt.Println(reverseReverse(sliceF,sliceH))
}
func reverseReverse(first []int, second []int) ([]int, []int){
//creating temp arrays to hold the traversed arrays before swapping.
var tempArr1 []int = first
var tempArr2 []int = second
//count is used for counting up the tempArrays in the correct order in the For loops
var count int= 0
//goes through the first array and sets the values starting from the end equal to the temp array
//which increases normally from left to right.
for i :=len(first)-1; i>=0;i--{
tempArr1[count] = first[i]
fmt.Println(i)
count++
}
count =0
//same as first for loop just on the second array
for i :=len(second)-1; i>=0;i--{
tempArr2[count] = second[i]
count++
}
//trying to replace the values of the param arrays to be equal to the temp arrays
first=tempArr2
second = tempArr1
//returning the arrays
return first,second
}
当运行时,这里是输出:
四
3
阿拉伯数字
1
0
[10 9 8 9 10]
[5 43 4 5]
*不是我在 for 循环中包含一个打印语句来检查索引是否正确减少。
我知道有更好的方法可以做到这一点,但为了证明概念,我想使用 for 循环。
任何帮助表示赞赏。 我是新手,并且倾向于有Java习惯,所以我认为我的问题与此有关。
通过意识到不需要实际交换单个元素,这可以简化得多。相反,反转每个数组并交换其顺序。简单多了!
func reverseReverse( a, b []int ) ([]int, []int) {
return reverse(b), reverse(a)
}
func reverse( a []int ) []int {
end := len(a) - 1
// Allocate a new array slice of the same length to copy to.
ret := make( []int, len(a) )
// Copy each element of a into ret, reversed.
for i := range a {
ret[end-i] = a[i]
}
return ret
}
有了这个启示,就几乎不需要非常专业的reverseReverse
功能了。自己交换订单。
fmt.Println(reverse(sliceH), reverse(sliceF))
请注意,如果您只想获取数组的一部分,则无需指定开始和结束即可写入sliceH []int := h[:]
。假定开始为 0,结束为结束。另请注意,无需声明类型,:=
会为您处理。
更好的是,您可以直接声明和初始化它们。
sliceF:= []int{1,2,3,4,5}
sliceH:= []int{6,7,8,9,10}
简短回答:
tempArr1[count] = first[i]
此行在逻辑上与以下内容相同:
first[count] = first[i]
详细答案:
x := [5]int{}
和x := []int{}
实际上是两个非常不同的任务。在第一种情况下x
实际上是一个静态数组。在第二种情况下,x
是一个切片,它实际上是一个数据结构,具有长度、容量和指向底层数组的指针。因此,var tempArr1 []int = first
表示将指向底层first
数组的指针复制到 tempArr1
中,因此对first[i]
的任何修改都将反映在tempArr1
中,反之亦然
,
package main
import "fmt"
func reverse(s []int) []int {
for i := 0; i < len(s)/2; i++ {
s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
}
return s
}
func main() {
s1, s2 := []int{1, 2, 3, 4, 5}, []int{6, 7, 8, 9, 10}
fmt.Println(s1, s2)
s1, s2 = reverse(s2), reverse(s1)
fmt.Println(s1, s2)
}
输出:
[1 2 3 4 5] [6 7 8 9 10]
[10 9 8 7 6] [5 4 3 2 1]