While exploring algorithms in Swift, couldn\'t find algorithm for array rotation in swift without using funcs shiftLeft
/ shiftRight
.
C has
We can do it using Array's dropFirst() and dropLast() functions.
func rotateLeft(arrToRotate: inout [Int], positions: Int){
if arrToRotate.count == 0 || positions == 0 || positions > arrToRotate.count{
print("invalid")
return
}
arrToRotate = arrToRotate.dropFirst(positions) + arrToRotate.dropLast(arrToRotate.count-positions)
}
var numbers : [Int] = [1, 2, 3, 4, 5]
rotateLeft(arrToRotate: &numbers, positions:2)
print(numbers) //prints [3, 4, 5, 1, 2]
You need to consider the scenario such as-
The number of rotation can be equal/more than the size of array you need to rotate.
To handle this scenario use modulo operator to find the actual number of rotation as you will find out rotating an array by a number equal to its size result in same array.
func rotateLeft(array:[Int],numberOfRotation:Int) -> [Int]
{
let offset = numberOfRotation % array.count
let tempResult = array[offset...] + array[..<offset]
return Array(tempResult)
}
We can use Slice
func rotLeft(a: [Int], d: Int) -> [Int] {
let slice1 = a[..<d]
let slice2 = a[d...]
return Array(slice2) + Array(slice1)
}
print(rotLeft(a:[1, 2, 3, 4, 5], d: 4))
//prints [5, 1, 2, 3, 4]
Why create a reverse function when we already have it in the Swift standard library? My solution (derived from Leo Dabus'):
extension Array {
mutating func rotate(positions: Int, size: Int? = nil) {
let size = size ?? count
guard positions < count && size <= count else { return }
self[0..<positions].reverse()
self[positions..<size].reverse()
self[0..<size].reverse()
}
}