Created
February 20, 2016 15:06
-
-
Save therealbnut/6dabf1c2e92c261b08e7 to your computer and use it in GitHub Desktop.
HackerRank Encryption
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
guard let response = readLine(stripNewline: true) else { | |
fatalError("Expecting input!") | |
} | |
let withoutSpaces = response.characters.filter { $0 != " " } | |
let length = withoutSpaces.count | |
let minRows = Int(floor(sqrt(Double(length)))) | |
let columns = minRows * minRows >= length ? minRows : minRows + 1 | |
var output = "" | |
output.reserveCapacity(length + columns) | |
for offset in 0 ..< columns { | |
let startIndex = withoutSpaces.startIndex.advancedBy(offset) | |
for index in startIndex.stride(to: withoutSpaces.endIndex, by: columns) { | |
output.append(withoutSpaces[index]) | |
} | |
output.append(Character(" ")) | |
} | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment