r/dailyprogrammer • 1 2 • Jan 07 '13

[01/07/13] Challenge #116 [Easy] Permutation of a string

(Easy): Permutation of a string

Write a function that prints all of the permutatons of the unique characters of a given string. For example, permute("baz") would print:

baz
bza
abz
azb
zba
zab

Find all the permutations of daily.

Author: skeeto

Formal Inputs & Outputs

Input Description

Your function should accept a single string variable which is guaranteed to be at least 1 character long.

Output Description

Print all permutations of the given string variable.

Sample Inputs & Outputs

Sample Input

Let the string argument be "ab"

Sample Output

All permutations of "ab" would be ["ab", "ba"]

Challenge Input

Let the string argument be "abbccc"

Challenge Input Solution

abbccc abcbcc abccbc abcccb acbbcc acbcbc acbccb accbbc accbcb acccbb babccc bacbcc baccbc bacccb bbaccc bbcacc bbccac bbccca bcabcc bcacbc bcaccb bcbacc bcbcac bcbcca bccabc bccacb bccbac bccbca bcccab bcccba cabbcc cabcbc cabccb cacbbc cacbcb caccbb cbabcc cbacbc cbaccb cbbacc cbbcac cbbcca cbcabc cbcacb cbcbac cbcbca cbccab cbccba ccabbc ccabcb ccacbb ccbabc ccbacb ccbbac ccbbca ccbcab ccbcba cccabb cccbab cccbba

Note

  • Bonus 1: Instead of printing, be functional. Return a collection (array, etc.) of the permutations.

  • Bonus 2: Correctly handle the case when the input contains a character multiple times. That is, don't output repeats and ensure the output contains the same number of characters as the input. For example, there are three permutations of foo: foo, ofo, oof.

  • Note that this challenge is a near-duplicate of challenge #12, hence why there is the above "bonus" challenges

63 Upvotes

100 comments sorted by

View all comments

6

u/nudan1 Jan 07 '13

C++: (hint: this problem screams recursion!)

#include <iostream>
#include <string>
 
void premute_string_aux (std::string prefix, std::string rest) 
{
    if (rest == "") {
        std::cout << prefix << std::endl;
    } else {
        for (int i = 0; i < rest.length (); i++) {
            if (rest.find (rest[i]) == i) {
                std::string new_prefix = prefix + rest[i];
                std::string new_rest = rest.substr (0, i) + rest.substr (i + 1);
                premute_string_aux (new_prefix, new_rest);
            }
        }
    }
}

void premute_string (std::string str) 
{
    premute_string_aux ("", str);
}

int main ()
{
    premute_string ("abbccc");
    
    return 0;
}

0

u/[deleted] Jan 16 '13

[deleted] — view deleted comment

2

u/nudan1 Jan 17 '13

Hello,

If you look at the reference documentation for the find function you will see that it returns a size_t type, which is integral, hence you can compare with i.