Calculate all permutations of a string in Swift

后端 未结 8 1314
余生分开走
余生分开走 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:17

    A very straightforward approach as also suggested in Swift coding challenges.

     func permutation(string: String, current: String = "") {
            let length = string.characters.count
            let strArray = Array(string.characters)
            if (length == 0) {
                // there's nothing left to re-arrange; print the result
                print(current)
                print("******")
            } else {
                print(current)
                // loop through every character
                for i in 0 ..< length {
                    // get the letters before me
                    let left = String(strArray[0 ..< i])
                    // get the letters after me
                    let right = String(strArray[i+1 ..< length])
                    // put those two together and carry on
                    permutation(string: left + right, current: current +
                        String(strArray[i]))
                }
    
            }
        }
    
    0 讨论(0)
  • 2020-12-03 04:18

    Here is my solution.

    import Foundation
    
    class Permutator {
        class func permutation(_ str: String) -> Set<String> {
             var set = Set<String>()
    
             permutation(str, prefix: "", set: &set)
    
             return set
        }
    
        private class func permutation(_ str: String, prefix: String, set: inout Set<String>) {
            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.

    0 讨论(0)
提交回复
热议问题