Calculate all permutations of a string in Swift

后端 未结 8 1354
余生分开走
余生分开走 2020-12-03 03:28

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

8条回答
  •  生来不讨喜
    2020-12-03 04:18

    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.

提交回复
热议问题