Created
February 22, 2017 15:46
-
-
Save AnthonyBY/3e9e52620fa2f31dcaf2caf696b0dba3 to your computer and use it in GitHub Desktop.
Arrays: Left Rotation Swift 3.1 Cracking the Coding Interview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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: " ") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 4 version ;)
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.