Skip to content

Instantly share code, notes, and snippets.

@StevenMasini
Last active July 8, 2017 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenMasini/a730423b2cbd83ecabd20f42e64acf2a to your computer and use it in GitHub Desktop.
Save StevenMasini/a730423b2cbd83ecabd20f42e64acf2a to your computer and use it in GitHub Desktop.
My implementation of the Permutation algorithm in Swift
class Permutator {
class func permutation(_ str: String) -> Set<String> {
return permutation(str, prefix: "")
}
private class func permutation(_ str: String, prefix: String) -> Set<String> {
if str.characters.count == 0 {
return [prefix]
}
var set = Set<String>()
for i in str.characters.indices {
let left = str.substring(to: i)
let right = str.substring(from: str.index(after: i))
let rem = left + right
set = set.union(permutation(rem, prefix: prefix + String(str[i])))
}
return set
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment