user3069232
user3069232

Reputation: 8995

Printing out all the combinations of a string

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 pairs and I should get 24. I cannot see what I have missed here.

Where this coding going wrong?

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)
}

It give me ...

CBDA DCBA ACDB ADCB ABDC ABCD DCAB ADCB BDAC BADC BCAD BCDA ADBC BADC CABD CBAD CDBA CDAB BACD CBAD DBCA DCBA DACB DABC

Upvotes: 4

Views: 1358

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236260

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"

Upvotes: 4

Gabriel Goncalves
Gabriel Goncalves

Reputation: 5160

Since you said: Trying to write a recursive function to show all the possible combinations of a string

I think you could so something like this:

// 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

Extracted from this answer which helped me a lot once: Calculate all permutations of a string in Swift

This would give you a number of permutations.

I hope this helps you.

Upvotes: 1

Related Questions