For the string \"ABC\" the code snippet below calculates 5 of the 6 total permutations. My strategy was to insert each character at each index possible index. B
Here is my solution.
import Foundation
class Permutator {
class func permutation(_ str: String) -> Set {
var set = Set()
permutation(str, prefix: "", set: &set)
return set
}
private class func permutation(_ str: String, prefix: String, set: inout Set) {
if str.characters.count == 0 {
set.insert(prefix)
}
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
permutation(rem, prefix: prefix + String(str[i]), set: &set)
}
}
}
let startTime = Date()
let permutation = Permutator.permutation("abcdefgh")
print("\(permutation) \n")
print("COMBINAISON: \(permutation.count)")
print("TIME: \(String(format: "%.3f", Date().timeIntervalSince(startTime)))s")
You can copy/paste it in a file and execute it with the command line swift binary.
For a permutation of 7 all unique characters, this algorithm take around 0,06 second to execute.