How to rotate slice elements left N times in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func rotateLeft(arr []int, positions int) []int {
    n := len(arr)
    positions = positions % n
    
    return append(arr[positions:], arr[:positions]...)
}

func main() {
    arr := []int{1, 2, 3, 4, 5, 6, 7}

    fmt.Println("Original array:", arr)

    rotated := rotateLeft(arr, 2)

    fmt.Println("Rotated array:", rotated)
}


/*
run:

Original array: [1 2 3 4 5 6 7]
Rotated array: [3 4 5 6 7 1 2]

*/

 



answered 23 hours ago by avibootz
...