Skip to content

Instantly share code, notes, and snippets.

@sameoldmadness
Created November 12, 2015 08:24
Show Gist options
  • Save sameoldmadness/8023fe509b26044c7581 to your computer and use it in GitHub Desktop.
Save sameoldmadness/8023fe509b26044c7581 to your computer and use it in GitHub Desktop.
Caesar cypher implementation in Swift
extension String {
var codePoint: UInt32? {
guard self.unicodeScalars.count == 1 else { return nil }
return self.unicodeScalars.first!.value
}
func mapCodePoints(fn: UInt32 -> UInt32) -> String {
return String(self.unicodeScalars.map { Character(UnicodeScalar(fn($0.value))) })
}
}
func rotate(code: UInt32, by offset: Int, withAdjustment adj: UInt32) -> UInt32 {
let azLength = 26
let normalizedOffset = UInt32((offset % azLength + azLength) % azLength)
return adj + ((code - adj + normalizedOffset) % UInt32(azLength))
}
func caesarize(str: String, withOffset offset: Int) -> String {
let A = "A".codePoint!, Z = "Z".codePoint!,
a = "a".codePoint!, z = "z".codePoint!
return str.mapCodePoints { code -> UInt32 in
switch code {
case A...Z:
return rotate(code, by: offset, withAdjustment: A)
case a...z:
return rotate(code, by: offset, withAdjustment: a)
default:
return code
}
}
}
caesarize("Ave, Caesar!", withOffset: -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment