所以我想寫一個需要兩個切片的方法,翻轉他們兩個,然後將它們給對方。用for循環邏輯錯誤翻轉切片
Ex。
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
}
當此處運行是輸出:
[10 9 8 9 10]
[ 5 4 3 4 5]
*我沒有在for循環中包含print語句來檢查索引是否正常遞減。
我知道有更好的方法來做到這一點,但爲了證明概念,我想使用for循環。
任何幫助表示讚賞。我是新來的,並傾向於有Java習慣,所以我假設我的問題與此有關。
得到它固定感謝您的幫助!我需要給切片一個長度,不知道如何,直到我看到你的製作方法,並查找它! – HoldenMalinchock
如果您不介意就地倒轉,則可以通過使用多變量賦值語法縮短。也減少了內存佔用。 https://play.golang.org/p/cCXEuQ3Nr5 – Kaedys
@Kaedys是,peterSO的回答演示倒車到位。有了好的陣列複製功能,就地版本將是首選。 – Schwern