Last active
September 18, 2020 15:18
-
-
Save tkausch/8ea253ea424a4a93e4a6a67316dfa741 to your computer and use it in GitHub Desktop.
How to calculate the ROT13 of a string
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
// ROT13 is a simple algorithm that shifts letters in a string forward 13 places. | |
struct ROT13 { | |
// create a dictionary that will store our character mapping | |
private static var key = [Character: Character]() | |
// create arrays of all uppercase and lowercase letters | |
private static let uppercase = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ") | |
private static let lowercase = Array("abcdefghijklmnopqrstuvwxyz") | |
static func string(_ string: String) -> String { | |
// if this is the first time the method is being called, calculate the ROT13 key dictionary | |
if ROT13.key.isEmpty { | |
for i in 0 ..< 26 { | |
ROT13.key[ROT13.uppercase[i]] = ROT13.uppercase[(i + 13) % 26] | |
ROT13.key[ROT13.lowercase[i]] = ROT13.lowercase[(i + 13) % 26] | |
} | |
} | |
// now return the transformed string | |
let transformed = string.map { ROT13.key[$0] ?? $0 } | |
return String(transformed) | |
} | |
} | |
extension String { | |
func rot13() -> String { | |
return ROT13.string(self) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment