1

For example if I have a string {a, b, c}. I need to print out on the console all the permutations without repeating letters from 1 letter to 3 letters like this:

a b c ab ac abc acb ba bc bac bca ca cb cab cba

How can I write this using recursion?

3
  • 1
    Which is it? Backtracking or recursion? I've done similar and it's usually been easier with backtracking. Also, you can do a "recursive" algorithm that uses a global stack but doesn't actually do genuine function recursion. Commented Apr 9, 2016 at 23:58
  • Possible duplicate of Algorithm to generate all possible permutations of a list? Commented Apr 10, 2016 at 0:05
  • @ChrisMartin The list does have cb and bc [and did before your edit]. So, probably permutations Commented Apr 10, 2016 at 0:18

1 Answer 1

1

If you need all the permutations of the chars into a String you can use a recursive function.

Here's the code in Swift.

func visit(unused:[Character], used: [Character] = [Character]()) -> [String] {
    var result = [String(used)]
    for (index, char) in unused.enumerate() {
        var unused = unused
        unused.removeAtIndex(index)
        var used = used
        used.append(char)
        result = result + visit(unused, used: used)
    }
    return result
}

As you can see the function receives 2 params:

  • unused: represents the list of chars not yet used
  • used: the chars used to build possible element of the ouput. This parameter is optional so if it's not passed to the function, an empty array is used (this is useful for the first invocation).

Test

let word = "abc"
let chars = [Character](word.characters)
print(visit(chars))

["", "a", "ab", "abc", "ac", "acb", "b", "ba", "bac", "bc", "bca", "c", "ca", "cab", "cb", "cba"]

Omitting the empty String

This results also contains the empty String but you can easily omit this value just update the function as shown below.

func visit(unused:[Character], used: [Character] = [Character]()) -> [String] {
    var result = [String]()
    if !used.isEmpty {
        result.append(String(used))
    }
    for (index, char) in unused.enumerate() {
        var unused = unused
        unused.removeAtIndex(index)
        var used = used
        used.append(char)
        result = result + visit(unused, used: used)
    }
    return result
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.