Printing out all the combinations of a string

后端 未结 2 568
陌清茗
陌清茗 2020-12-17 05:26

iOS 11, Swift 4.0

Trying to write a recursive function to show all the possible combinations of a string. I got this, but its not quite right since I get only 20 pa

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 05:47

    Not a direct answer to your question but you can get all permutations (translated from java to Swift) as follow:

    public extension RangeReplaceableCollection {
        func permutations() -> [SubSequence] {
            isEmpty ? [] : permutate(.init())
        }
        private func permutate(_ subSequence: SubSequence) -> [SubSequence] {
            var permutations = isEmpty ? [subSequence] : []
            indices.forEach {
                permutations += (self[..<$0] + self[$0...].dropFirst())
                    .permutate(subSequence + CollectionOfOne(self[$0]))
            }
            return permutations
        }
    }
    

    let str = "ABCD"
    print(str.permutations())   // "["ABCD", "ABDC", "ACBD", "ACDB", "ADBC", "ADCB", "BACD", "BADC", "BCAD", "BCDA", "BDAC", "BDCA", "CABD", "CADB", "CBAD", "CBDA", "CDAB", "CDBA", "DABC", "DACB", "DBAC", "DBCA", "DCAB", "DCBA"]\n"
    

    Per-mutating a substring

    print("ABCD".dropLast().permutations())   // ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]\n"
    

提交回复
热议问题