Go語言陣列旋轉程式
介紹
在本教程中,我們將學習如何編寫一個 Go 語言程式來旋轉陣列。我們將為此編寫兩個程式。一個用於向左旋轉陣列,另一個用於向右旋轉陣列。
Go語言陣列向左旋轉程式
以下程式碼說明了如何使用使用者定義函式向左旋轉陣列。
上述程式的演算法
步驟 1 − 匯入 fmt 包,該包允許我們在螢幕上列印任何內容。
步驟 2 − 建立一個名為 rotateLeft() 的函式,該函式在旋轉陣列後返回最終陣列。
步驟 3 − 此函式使用 for 迴圈遍歷陣列,並在每次迭代中呼叫 rotateLeftByOne() 函式。
步驟 4 − 此函式將陣列作為引數,並使用 for 迴圈遍歷陣列變數。
步驟 5 − 在每次迭代中,我們將下一個值放置到前一個位置,並恢復第一個元素。
步驟 6 − 現在呼叫 main() 函式。
步驟 7 − 初始化一個整數陣列併為其賦值。
步驟 8 − 在螢幕上列印陣列,並透過將陣列和元素應移動的次數作為引數傳遞給函式來呼叫 rotateLeft() 函式。
步驟 9 − 使用 fmt.Println() 函式在螢幕上列印最終陣列。
示例
package main
import "fmt"
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, 7)
fmt.Println("The array obtained by rotating it to left by 7 positions is:", arr)
}
輸出
The entered array is: [1 2 3 4 5 6 7 8] The array obtained by rotating it to left by 7 positions is: [8 1 2 3 4 5 6 7]
Go語言陣列向右旋轉程式
以下程式碼說明了一個 Go 語言程式,用於將陣列元素向右旋轉任意次數。
上述程式的演算法
步驟 1 − 匯入 fmt 包,該包允許我們在螢幕上列印任何內容。
步驟 2 − 定義一個名為 rotateRight() 的函式,該函式將陣列向右旋轉任意次數。
步驟 3 − 它使用 for 迴圈遍歷陣列並將倒數第二個元素儲存在一個變數中。
步驟 4 − 然後它使用另一個 for 迴圈將元素向右移動到陣列的長度。
步驟 5 − 啟動 main() 函式。這是程式的起點,從這裡開始執行。
步驟 6 − 初始化一個整數陣列併為其賦值。在螢幕上列印此陣列。
步驟 7 − 現在透過將陣列和應移動的次數作為引數傳遞給它來呼叫 rotateRight() 函式。
步驟 8 − 使用 fmt.Println() 函式在螢幕上列印最終陣列。
示例
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}
// printing the array on the screen using fmt.Println() function
fmt.Println("The entered array is:", arr)
rotateRight(arr, 7)
fmt.Println("The array obtained by rotating it to right by 7 positions is:", arr)
}
輸出
The entered array is: [1 2 3 4 5 6 7 8] The array obtained by rotating it to right by 7 positions is: [2 3 4 5 6 7 8 1]
使用預定義函式向右旋轉陣列
現在讓我們看看另一個程式,使用該程式我們可以向右旋轉陣列變數,但無需使用迴圈和條件語句。
語法
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, 7)
fmt.Println("The array obtained by rotating it to right by 7 positions is:", arr)
}
輸出
The entered array is: [1 2 3 4 5 6 7 8] The array obtained by rotating it to right by 7 positions is: [2 3 4 5 6 7 8 1]
結論
我們已經成功編譯並執行了一個 Go 語言程式來旋轉陣列的元素以及示例。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP