Arrays: Left Rotation
Problem statement
A left rotation operation on an Slice shifts each elements o the slice 1 position to the left, and the one who is at first place will be colocated on the last position and so on.
Considerations
Given the signature of our function:
We need to be carefull with one detail, if d
the number of left rotation to be performed is greater than len(a)
the length of the slice. Our following operation will panic. panic: runtime error: slice bounds out of range [:d] with capacity cap
Hopefully we can recalculate the number of positions we need to slice in order to rotate the array without panic.
The mod operator
The mod operator works in the following way, no matter how big the numbers of rotations will be it always fall into a shift of positions on the Slice. For instance for an [1 2 3 4 5]
Slice of len(5)
it will be same to rotate it 6
positions instead of 11
or 16
because it turns out that for an Slice of this length it will always comes to rotate just1
position. And how come will array to this number?
The algorithm
- The function checks if
d
is greater than the length of the arraya
. If it is, then the function calculates the modulus ofd
and uses that value as the actual rotation to be performed. - The function slices the array
a
at thed
th position. The first slice,left
, contains the firstd
elements of the array. The second slice,right
, contains the remaining elements of the array. - The function joins the two slices together, starting with the
right
slice and then appending the reversedleft
slice.
Resources
I ask Google Bard to explain my code.