To rotate elements in an array using Go, you can implement a custom rotation function that shifts elements by a specified number of positions.
In this example,
intArray
containing integers.rotate
function that shifts elements by a specified number of positions.package main
import (
"fmt"
)
func rotateArray(array []int, positions int) []int {
n := len(array)
positions %= n
reverseArray(array, 0, n-1)
reverseArray(array, 0, positions-1)
reverseArray(array, positions, n-1)
return array
}
func reverseArray(array []int, start int, end int) {
for start < end {
array[start], array[end] = array[end], array[start]
start++
end--
}
}
func main() {
intArray := []int{1, 2, 3, 4, 5}
fmt.Println("Rotated Array:", rotateArray(intArray, 2))
}
Rotated Array: [4 5 1 2 3]
In this example,
strArray
containing strings.rotate
function that shifts elements by a specified number of positions.package main
import (
"fmt"
)
func rotateArray(array []string, positions int) []string {
n := len(array)
positions %= n
reverseArray(array, 0, n-1)
reverseArray(array, 0, positions-1)
reverseArray(array, positions, n-1)
return array
}
func reverseArray(array []string, start int, end int) {
for start < end {
array[start], array[end] = array[end], array[start]
start++
end--
}
}
func main() {
strArray := []string{"apple", "banana", "cherry", "date", "fig"}
fmt.Println("Rotated Array:", rotateArray(strArray, 3))
}
Rotated Array: [cherry date fig apple banana]
In this tutorial, we learned How to Rotate Elements in an Array in Go language with well detailed examples.