打印出字符串的所有组合

时间:2017-11-04 19:59:39

标签: ios swift recursion

iOS 11,Swift 4.0

尝试编写递归函数以显示字符串的所有可能组合。我得到了这个,但它不太正确,因为我只有20对,我应该得到24.我看不出我错过了什么。

这个编码出错的地方?

var ans:Set<String>!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let str = "ABCD"
    ans = []
    recursiveString(s2s: str, char2s: 0)
    print("\(ans) \(ans.count)")
}

func recursiveSwap(s2x: String, c2x: Int, j2m: Int) {
    var anschr = Array(s2x)
        let tmpchr = anschr[c2x]
        anschr[c2x] = anschr[c2x+j2m]
        anschr[c2x+j2m] = tmpchr
        print("\(String(anschr))")
            ans.insert(String(anschr))
        if (c2x + j2m + 1) < s2x.count {
            recursiveSwap(s2x: String(s2x), c2x: c2x, j2m: j2m+1)
        } else {
            if (c2x + 1) < s2x.count - 1 {
                recursiveSwap(s2x: String(anschr), c2x: c2x + 1, j2m: 1)
            }
        }
}

func recursiveString(s2s: String, char2s: Int) {
    let blue = shiftString(s2s: s2s)
    if char2s < s2s.count {
        recursiveSwap(s2x: blue, c2x: 0, j2m: 1)
        recursiveString(s2s: blue, char2s: char2s + 1)
    }
}

func shiftString(s2s: String) -> String {
    let str2s = Array(s2s)
    let newS = str2s.suffix(str2s.count - 1)  + str2s.prefix(1)
    return String(newS)
}

它给了我......

CBDA DCBA ACDB ADCB ABDC A B C D DCAB ADCB BDAC BADC BCAD BCDA 中国农业发展银行 BADC CABD CBAD CDBA CDAB BACD CBAD DBCA DCBA DACB DABC

2 个答案:

答案 0 :(得分:3)

不是您问题的直接答案,但您可以获得所有permutations(从java翻译为Swift),如下所示:

public extension StringProtocol where Self: RangeReplaceableCollection {
    var permutations: Set<String> {
        guard !isEmpty else { return [] }
        permutate(Self(), self[...])
        return String.permutations
    }
    private func permutate(_ result: Self, _ string: SubSequence) {
        if string.isEmpty {
            String.permutations.insert(result.string)
        } else {
            string.lazy.indices.forEach {
                permutate(result + [string[$0]], string[..<$0] + string[string.index(after: $0)...])
            }
        }
    }
}
fileprivate extension String {
    static var permutations: Set<String> = []
}
public extension LosslessStringConvertible {
    var string: String { return String(self) }
}
let str = "ABCD"
print(str.permutations.sorted())   // "["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 substring

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

答案 1 :(得分:0)

既然你说过:Trying to write a recursive function to show all the possible combinations of a string

我认为你可以这样:

// Takes any collection of T and returns an array of permutations
func permute<C: Collection>(items: C) -> [[C.Iterator.Element]] {
    var scratch = Array(items) // This is a scratch space for Heap's algorithm
    var result: [[C.Iterator.Element]] = [] // This will accumulate our result

    // Heap's algorithm
    func heap(_ n: Int) {
        if n == 1 {
            result.append(scratch)
            return
        }

        for i in 0..<n-1 {
            heap(n-1)
            let j = (n%2 == 1) ? 0 : i
            scratch.swapAt(j, n-1)
        }
        heap(n-1)
    }

    // Let's get started
    heap(scratch.count)

    // And return the result we built up
    return result
}

// We could make an overload for permute() that handles strings if we wanted
// But it's often good to be very explicit with strings, and make it clear
// that we're permuting Characters rather than something else.

let string = "ABCD"
let perms = permute(string.characters) // Get the character permutations
let permStrings = perms.map() { String($0) } // Turn them back into strings
print(permStrings) // output if you like

从这个答案中摘录了很多次:Calculate all permutations of a string in Swift

这会给你一些排列。

我希望这会对你有所帮助。