Created
August 4, 2014 21:36
-
-
Save jeremy-w/2c638619ba302dea6b8a to your computer and use it in GitHub Desktop.
Demonstrates rot13 in Swift with non-[A-Z][a-z] pass-through.
This file contains hidden or 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
import Cocoa | |
var input = "This is a test" | |
var expected = "Guvf vf n grfg" | |
/// Advances `i` by `by` through `string`, wrapping to start on hitting | |
/// end. | |
/// NOTE: `by` must be non-negative. | |
func wrappingAdvance(string: String, i: String.Index, by: Int) | |
-> String.Index { | |
assert(by > 0) | |
var left = by | |
var j = i | |
let s = string.startIndex | |
let e = string.endIndex | |
while left > 0 { | |
j = j.successor() | |
if j == e { | |
j = s | |
} | |
left -= 1 | |
} | |
return j | |
} | |
/// Returns the string with A-Za-z rotated. | |
func rot13(text: String) -> String { | |
let uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
let lowercase = uppercase.lowercaseString | |
let count: Int = countElements(uppercase) | |
let rotation = count / 2 | |
assert(countElements(lowercase) == count) | |
var output = "" | |
for ch in text { | |
if let i = find(uppercase, ch) { | |
let rotated = wrappingAdvance(uppercase, i, rotation) | |
output += uppercase[rotated] | |
} else if let i = find(lowercase, ch) { | |
let rotated = wrappingAdvance(lowercase, i, rotation) | |
output += lowercase[rotated] | |
} else { | |
output += ch | |
} | |
} | |
return output | |
} | |
rot13(input) == expected | |
"été" == rot13(rot13("été")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's another go, a little shorter but less elegant: https://gist.github.com/shepting/bdeab98418410fdeedc9