Skip to content

Instantly share code, notes, and snippets.

@therealbnut
Created February 20, 2016 15:06
Show Gist options
  • Save therealbnut/6dabf1c2e92c261b08e7 to your computer and use it in GitHub Desktop.
Save therealbnut/6dabf1c2e92c261b08e7 to your computer and use it in GitHub Desktop.
HackerRank Encryption
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