Skip to content

Instantly share code, notes, and snippets.

@AnthonyBY
Created February 22, 2017 15:46
Show Gist options
  • Save AnthonyBY/3e9e52620fa2f31dcaf2caf696b0dba3 to your computer and use it in GitHub Desktop.
Save AnthonyBY/3e9e52620fa2f31dcaf2caf696b0dba3 to your computer and use it in GitHub Desktop.
Arrays: Left Rotation Swift 3.1 Cracking the Coding Interview
// MARK : This is not very elegant solution, but working with input/output is really not nice on Swift 3.1
// so this just an example for working with input Sample Input like:
// 5 4
// 1 2 3 4 5
// in Arrays: Left Rotation (
import Foundation
func rotate(arr: [Int], offset: Int) -> [Int] {
var newArray = [Int]()
var newOffSet = offset
if (newOffSet > arr.count) {
newOffSet = offset % arr.count
}
for index in newOffSet...arr.count-1 {
newArray.append(arr[index])
}
for index in 0...offset-1 {
newArray.append(arr[index])
}
return newArray
}
// Read array with n elements with " " separated
var input = readLine()!.components(separatedBy: " ").map{ Int($0)! }
var n = input[0]
var d = input[1]
var arr = readLine()!.components(separatedBy: " ").map{ Int($0)! }
for i in rotate(arr: arr, offset: d) {
print(i, terminator: " ")
}
@dyrkabes
Copy link

dyrkabes commented Jul 1, 2018

Swift 4 version ;)

extension Array {
    func rotateLeft(offset: Int) -> [Element] {
        let properOffset = offset % self.count
        let result = self[properOffset...] + self[..<properOffset]
        return Array(result)
    }
}

And a more generalized version that handles both right and left.. but this one is not that easy to read and it's not obvious which way the negative sign will rotate the array.

extension Array {
    func rotate(offset: Int) -> [Element] {
        let properOffset = offset % self.count
        let result: ArraySlice<Element>
        if properOffset > 0 {
            result = self[properOffset...] + self[..<properOffset]
        } else {
            let terminalOffset = count + properOffset
            result = self[(terminalOffset)...] + self[..<terminalOffset]
        }
        return Array(result)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment