views:

1666

answers:

14
void permute(string elems, int mid, int end)
{
    static int count;
    if (mid == end) {
        cout << ++count << " : " << elems << endl;
        return ;
    }
    else {
    for (int i = mid; i <= end; i++) {
            swap(elems, mid, i);
            permute(elems, mid + 1, end);
            swap(elems, mid, i);
        }
    }
}

The above function shows the permutations of str(with str[0..mid-1] as a steady prefix, and str[mid..end] as a permutable suffix). So we can use permute(str, 0, str.size() - 1) to show all the permutations of one string.

But the function uses a recursive algorithm; maybe its performance could be improved?

Are there any better methods to permute a string?

+9  A: 

See STL permutations.

In particular, you want std::next_permutation.

void permute(string elems, int mid, int end)
{
  int count = 0;
  while(next_permutation(elems.begin()+mid, elems.end()))
    cout << << ++count << " : " << elems << endl;
}

... or something like that...

Kornel Kisielewicz
+33  A: 

Why dont you try std::next_permutation() or std::prev_permutation() ?

Links:

std::next_permutation()
std::prev_permutation()

A simple example:

#include<string>
#include<iostream>
#include<algorithm>

int main()
{
   std::string s="123";
   do
   {

      std::cout<<s<<std::endl;

   }while(std::next_permutation(s.begin(),s.end()));
}

Output:

123
132
213
231
312
321
Prasoon Saurav
keep in mind that in order to get all permutations your initial string/array must be sorted in ascending order.
Omry
I think the STL has to re-examine the sequence each time it is called. The code in the question doesn't have to do any comparisons, so I think that might be more efficient (plus, it would work even on types that don't support `<`).
Jason Orendorff
http://wordaligned.org/articles/next-permutation
sdcvvc
Omry: INCORRECT. It goes in a cycle. The next permutation of the greatest permutation is the least permutation.
Potatoswatter
Using the return `bool` return value as the condition, you're correct, though.
Potatoswatter
Remember, STL was invented by crazed mathematicians. Seriously, if you apply the algorithms correctly, you get high efficiency. And it's all part of C++!
Jon Reid
If the STL were really crazy math, it would have these: http://en.wikipedia.org/wiki/Fibonacci_heap
Potatoswatter
+4  A: 

Any algorithm for generating permutations is going to run in polynomial time, because the number of permutations for characters within an n-length string is (n!). That said, there are some pretty simple in-place algorithms for generating permutations. Check out the Johnson-Trotter algorithm.

JohnE
n! is not polynomial, so no algorithm will be able to run in polynomial time.
tster
+1 Johnson-Trotter is the way to go
Thorsten S.
A: 

Obligatory Python example:

def permute(elems):
    from itertools import permutations
    for i, s in enumerate(permutations(elems), 1):
        print i, ":", "".join(s)
Matt Joiner
The question is tagged with C++ and the example code given is C++. I don't think posting a Python snippet is appropriate.
larsm
You can do all sorts of things with python that aren't immediately obvious in C++. This isn't a valid answer.
Chinmay Kanchi
The easiest way to stop getting negative marks is to delete the answer. :-) Everything the above people said is true.
Omnifarious
Nah it's worth watching people rage. Do I get my marks back if I delete the answer?
Matt Joiner
You realize that makes you the very definition of a troll. I hope not. Only 8 points anyway!
Potatoswatter
+3  A: 

Any algorithm that makes use of or generates all permutations will take O(N!*N) time, O(N!) at the least to generate all permutations and O(N) to use the result, and that's really slow. Note that printing the string is also O(N) afaik.

In a second you can realistically only handle strings up to a maximum of 10 or 11 characters, no matter what method you use. Since 11!*11 = 439084800 iterations (doing this many in a second on most machines is pushing it) and 12!*12 = 5748019200 iterations. So even the fastest implementation would take about 30 to 60 seconds on 12 characters.

Factorial just grows too fast for you to hope to gain anything by writing a faster implementation, you'd at most gain one character. So I'd suggest Prasoon's recommendation. It's easy to code and it's quite fast. Though sticking with your code is completely fine as well.

I'd just recommend that you take care that you don't inadvertantly have extra characters in your string such as the null character. Since that will make your code a factor of N slower.

JPvdMerwe
+18  A: 

Here is a non-recursive algorithm in C++ from the Wikipedia entry for unordered generation of permutations. For the string s of length n, for any k from 0 to n! - 1 inclusive, the following modifies s to provide a unique permutation (that is, different from those generated for any other k value on that range). To generate all permutations, run it for all n! k values on the original value of s.

void permutation(int k, string &s) 
{
    for(int j = 1; j < s.size(); ++j) 
    {
        swap(s, k % (j + 1), j); 
        k = k / (j + 1);
    }
}

Here swap(s, i, j) swaps position i and j of the string s.

Permaquid
Someone selected the answer that said your answer was the best one. *sigh* And your answer is the best one.
Omnifarious
Such is life. The best-laid plans o mice and men gang aft agley.
Permaquid
+1  A: 

I've written a permutation algorithm recently. It uses a vector of type T (template) instead of a string, and it's not super-fast because it uses recursion and there's a lot of copying. But perhaps you can draw some inspiration for the code. You can find the code here.

StackedCrooked
`concat` is just an inferior version of `v.insert(v.begin(), item)`. `GetPermutations` just does the same thing as OP's code, which is inferior to a loop with `std::next_permutation`.
Potatoswatter
I never claimed my solution to be superior :) That said, I don't see how my GetPermutations function is the same as the OP's code.
StackedCrooked
Each call partitions the string into a stable and a recursively permuted part.
Potatoswatter
+1  A: 

The only way to significantly improve performance is to find a way to avoid iterating through all the permutations in the first place!

Permuting is an unavoidably slow operation (O(n!), or worse, depending on what you do with each permutation), unfortunately nothing you can do will change this fact.

Also, note that any modern compiler will flatten out your recursion when optimisations are enabled, so the (small) performance gains from hand-optimising are reduced even further.

Autopulated
+14  A: 

I'd like to second Permaquid's answer. The algorithm he cites works in a fundamentally different way from the various permutation enumeration algorithms that have been offered. It doesn't generate all of the permutations of n objects, it generates a distinct specific permutation, given an integer between 0 and n!-1. If you need only a specific permutation, it's much faster than enumerating them all and then selecting one.

Even if you do need all permutations, it provides options that a single permutation enumeration algorithm does not. I once wrote a brute-force cryptarithm cracker, that tried every possible assignment of letters to digits. For base-10 problems, it was adequate, since there are only 10! permutations to try. But for base-11 problems took a couple of minutes and base-12 problems took nearly an hour.

I replaced the permutation enumeration algorithm that I had been using with a simple i=0--to--N-1 for-loop, using the algorithm Permaquid cited. The result was only slightly slower. But then I split the integer range in quarters, and ran four for-loops simultaneously, each in a separate thread. On my quad-core processor, the resulting program ran nearly four times as fast.

Just as finding an individual permutation using the permutation enumeration algorithms is difficult, generating delineated subsets of the set of all permutations is also difficult. The algorithm that Permaquid cited makes both of these very easy

Jeff Dege
Another thought - the algorithm maps permutations to an integer between 0 and n!-1, which quickly overflows any reasonable integer size.If you need to work with larger permutations, you need an extended integer representation. In this case, a factoradic representation will serve you best. In a factoradic representation, instead of each digit representing a multiple of 10^k, each digit represents a multiple of k!.There is a direct algorithm for mapping a factoradic representation into a permutation. You can find details at http://en.wikipedia.org/wiki/Factoradic#Permutations
Jeff Dege
+2  A: 

The Knuth random shuffle algorithm is worth looking into.

// In-place shuffle of char array
void shuffle(char array[], int n)
{
    for ( ; n > 1; n--)
    {
        // Pick a random element to move to the end
        int k = rand() % n;  // 0 <= k <= n-1  

        // Simple swap of variables
        char tmp = array[k];
        array[k] = array[n-1];
        array[n-1] = tmp;
    }
}
Loadmaster
How is this relevant?
Oddthinking
Oh, never mind, I didn't read the problem closely enough. OP wants *all* permutations, not just one.
Loadmaster
+1  A: 

Do you want to run through all the permutations, or count the number of permutations?

For the former, use std::next_permutation as suggested by others. Each permutation takes O(N) time (but less amortized time) and no memory except its callframe, vs O(N) time and O(N) memory for your recursive function. The whole process is O(N!) and you can't do better than this, as others said, because you can't get more than O(X) results from a program in less than O(X) time! Without a quantum computer, anyway.

For the latter, you just need to know how many unique elements are in the string.

big_int count_permutations( string s ) {
    big_int divisor = 1;
    sort( s.begin(), s.end() );
    for ( string::iterator pen = s.begin(); pen != s.end(); ) {
        size_t cnt = 0;
        char value = * pen;
        while ( pen != s.end() && * pen == value ) ++ cnt, ++ pen;
        divisor *= big_int::factorial( cnt );
    }
    return big_int::factorial( s.size() ) / divisor;
}

Speed is bounded by the operation of finding duplicate elements, which for chars can be done in O(N) time with a lookup table.

Potatoswatter
-1 The algorithm you use to count is wrong.
Jichao
Any constructive criticism, or an example of input for which it fails?
Potatoswatter
Jichao
ah, correct. By the way, do you want permutations of unique elements, (n!) total, as your algo returns, or unique permutations, as counted by this?
Potatoswatter
actually,I hanv't consider unique before,i assume elements of the input string are unique in my alg.
Jichao
notice there are many other problems in your algorithm.here is my version to count unique permutations:http://code.google.com/p/jcyangs-alg-trunk/source/browse/trunk/recur/permutation/count/MyCount.cc
Jichao
Other problems such as what? Add `++pen` after `++cnt`. You shouldn't use `double` as a bignum class, by the way. Hmm, looking at my code, the call to `sort` isn't O(N). Whatever.
Potatoswatter
have you tested your code?simple case `abc` would produce wrong answer or even crash the program.
Jichao
i haven't use `uint64` before and `<cstdint>` would bring protability problem.definitly,i would update the code later.`the call to sort isn't O(n)`,what do you mean by this?
Jichao
I hadn't tested it before, but now that you ask, yes, it appears to work correctly once you add `++cnt`.
Potatoswatter
`uint64` also isn't a bignum class. You can use whatever kind of number you want; in any case, be sure you don't overflow. `sort` doesn't run in O(N) time, it's O(N log N).
Potatoswatter
it didn't work.`while ( pen != s.end() `,while pen iterate to the end of the string,cnt become 0,then divisor should be 0 too,which lead to the wrong result.
Jichao
antoher problem lies in your alg.Considering input 'aabbc',your alg would produce `5! / (2! * 2!)`,but the right answer should be `c(5,2) * c(3,2) * 1!`.
Jichao
1. `cnt` will always be advanced at least once. 2: factorial(0) = 1 even if it weren't. 3. C(n,k) = n!/(k!(n-k)!) so C(5,2)*C(3,2) = 5!3!/(2!3!2!1!) = 5!/(2!2!). You can work through the algebra to see they're always the same.
Potatoswatter
correct.i'm wrong.i didn't use the standard factorial function.and your alg is much cleaner than mine.anyway thanks.
Jichao
downvote cleaned.thanks for your answer agian.
Jichao
Lol, thx, I didn't even think you could do that. Usually (on other people's questions I guess) the vote locks in after about a minute.
Potatoswatter
not exactly.after you editing twice,the lock will be cleaned.
Jichao
good to know :)
Potatoswatter
+1  A: 

I don't think this is better, but it does work and does not use recursion:

#include <iostream>
#include <stdexcept>
#include <tr1/cstdint>

::std::uint64_t fact(unsigned int v)
{
   ::std::uint64_t output = 1;
   for (unsigned int i = 2; i <= v; ++i) {
      output *= i;
   }
   return output;
}

void permute(const ::std::string &s)
{
   using ::std::cout;
   using ::std::uint64_t;
   typedef ::std::string::size_type size_t;

   static unsigned int max_size = 20;  // 21! > 2^64

   const size_t strsize = s.size();

   if (strsize > max_size) {
      throw ::std::overflow_error("This function can only permute strings of size 20 or less.");
   } else if (strsize < 1) {
      return;
   } else if (strsize == 1) {
      cout << "0 : " << s << '\n';
   } else {
      const uint64_t num_perms = fact(s.size());
      // Go through each permutation one-by-one
      for (uint64_t perm = 0; perm < num_perms; ++perm) {
         // The indexes of the original characters in the new permutation
         size_t idxs[max_size];

         // The indexes of the original characters in the new permutation in
         // terms of the list remaining after the first n characters are pulled
         // out.
         size_t residuals[max_size];

         // We use div to pull our permutation number apart into a set of
         // indexes.  This holds what's left of the permutation number.
         uint64_t permleft = perm;

         // For a given permutation figure out which character from the original
         // goes in each slot in the new permutation.  We start assuming that
         // any character could go in any slot, then narrow it down to the
         // remaining characters with each step.
         for (unsigned int i = strsize; i > 0; permleft /= i, --i) {
            uint64_t taken_char = permleft % i;
            residuals[strsize - i] = taken_char;

            // Translate indexes in terms of the list of remaining characters
            // into indexes in terms of the original string.
            for (unsigned int o = (strsize - i); o > 0; --o) {
               if (taken_char >= residuals[o - 1]) {
                  ++taken_char;
               }
            }
            idxs[strsize - i] = taken_char;
         }
         cout << perm << " : ";
         for (unsigned int i = 0; i < strsize; ++i) {
            cout << s[idxs[i]];
         }
         cout << '\n';
      }
   }
}

The fun thing about this is that the only state it uses from permutation to permutation is the number of the permutation, the total number of permutations, and the original string. That means it can be easily encapsulated in an iterator or something like that without having to carefully preserve the exact correct state. It can even be a random access iterator.

Of course ::std::next_permutation stores the state in the relationships between elements, but that means it can't work on unordered things, and I would really wonder what it does if you have two equal things in the sequence. You can solve that by permuting indexes of course, but that adds slightly more complication.

Mine will work with any random access iterator range provided it's short enough. And if it isn't, you'll never get through all the permutations anyway.

The basic idea of this algorithm is that every permutation of N items can be enumerated. The total number is N! or fact(N). And any given permutation can be thought of as a mapping of source indices from the original sequence into a set of destination indices in the new sequence. Once you have an enumeration of all permutations the only thing left to do is map each permutation number into an actual permutation.

The first element in the permuted list can be any of the N elements from the original list. The second element can be any of the N - 1 remaining elements, and so on. The algorithm uses the % operator to pull apart the permutation number into a set of selections of this nature. First it modulo's the permutation number by N to get a number from [0,N). It discards the remainder by dividing by N, then it modulo's it by the size of the list - 1 to get a number from [0,N-1) and so on. That is what the for (i = loop is doing.

The second step is translating each number into an index into the original list. The first number is easy because it's just a straight index. The second number is an index into a list that contains every element but the one removed at the first index, and so on. That is what the for (o = loop is doing.

residuals is a list of indices into the successively smaller lists. idxs is a list of indices into the original list. There is a one-one mapping between values in residuals and idxs. They each represent the same value in different 'coordinate spaces'.

The answer pointed to by the answer you picked has the same basic idea, but has a much more elegant way of accomplishing the mapping than my rather literal and brute force method. That way will be slightly faster than my method, but they are both about the same speed and they both have the same advantage of random access into permutation space which makes a whole number of things easier, including (as the answer you picked pointed out) parallel algorithms.

Omnifarious
could you explain it a bit more.this alg is hard to me.
Jichao
This is a poor variant of the answer actually selected.
Omnifarious
one more trivial question:what compiler do you use?whats tr1 in the `<tr1/stdint>`?
Jichao
I use g++ 4.4.x. TR1 is an interim standard for adding a few things to the C++ standard library. All headers that are part of TR1 will have tr1/ in front of them. See http://en.wikipedia.org/wiki/C%2B%2B_Technical_Report_1
Omnifarious
And the new C99 `stdint.h` header isn't part of C++, but with TR1 they added it as `<tr1/cstdint>`.
Omnifarious
A: 

This post: http://cplusplus.co.il/2009/11/14/enumerating-permutations/ deals with permuting just about anything, not only strings. The post itself and the comments below are pretty informative and I wouldn't want to copy&paste..

rmn
A: 

If you are interested in permutation generation I did a research paper on it a while back : http://www.oriontransfer.co.nz/research/permutation-generation

It comes complete with source code, and there are 5 or so different methods implemented.

Mr Samuel