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語言程式,用於旋轉陣列的元素以及示例。

更新於:2023年2月10日

瀏覽量:529

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.