Are there any better methods to do permutation of string?

前端 未结 20 1368
醉话见心
醉话见心 2020-11-27 11:15
void permute(string elems, int mid, int end)
{
    static int count;
    if (mid == end) {
        cout << ++count << \" : \" << elems << end         


        
相关标签:
20条回答
  • 2020-11-27 11:42
      //***************anagrams**************//
    
    
      //************************************** this code works only when there are no   
      repeatations in the original string*************//
      #include<iostream>
      using namespace std;
    
      int counter=0;
    
      void print(char empty[],int size)
      {
    
      for(int i=0;i<size;i++)
      {
        cout<<empty[i];
      }
      cout<<endl;
      }
    
    
      void makecombination(char original[],char empty[],char comb[],int k,int& nc,int size)
    {
    nc=0;
    
    int flag=0;
    for(int i=0;i<size;i++)
    {
        flag=0;                                                                   // {
        for(int j=0;j<k;j++)
        {
            if(empty[j]==original[i])                                                                // remove this code fragment
            {                                                                                        // to print permutations with repeatation
                flag=1;
                break;
            }
        }
        if(flag==0)                                                                // }
        {
            comb[nc++]=original[i];
        }
    }
    //cout<<"checks  ";
    //    print(comb,nc);
    }
    
    
    void recurse(char original[],char empty[],int k,int size)
    {
    char *comb=new char[size];
    
    
    int nc;
    
    
    if(k==size)
    {
        counter++;
        print(empty,size);
        //cout<<counter<<endl;
    
    }
    else
    {
        makecombination(original,empty,comb,k,nc,size);
        k=k+1;
        for(int i=0;i<nc;i++)
        {
            empty[k-1]=comb[i];
    
            cout<<"k = "<<k<<" nc = "<<nc<<" empty[k-1] = "<<empty[k-1]<<endl;//checks the  value of k , nc, empty[k-1] for proper understanding
            recurse(original,empty,k,size);
        }
    }
    
    }
    
    int main()
    {
    const int size=3;
    int k=0;
    char original[]="ABC";
    
    char empty[size];
    for(int f=0;f<size;f++)
    empty[f]='*';
    
    recurse(original,empty,k,size);
    
    cout<<endl<<counter<<endl;
    return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 11:43

    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.

    0 讨论(0)
  • 2020-11-27 11:44
    **// Prints all permutation of a string**
    
        #include<bits/stdc++.h>
        using namespace std;
    
    
        void printPermutations(string input, string output){
            if(input.length() == 0){
                cout<<output <<endl;
                return;
            }
    
            for(int i=0; i<=output.length(); i++){
                printPermutations(input.substr(1),  output.substr(0,i) + input[0] + output.substr(i));
            }
        }
    
        int main(){
            string s = "ABC";
            printPermutations(s, "");
            return 0;
        }
    
    0 讨论(0)
  • 2020-11-27 11:47

    Here yet another recursive function for string permutations:

    void permute(string prefix, string suffix, vector<string> &res) {
        if (suffix.size() < 1) {
            res.push_back(prefix);
            return;
        }
        for (size_t i = 0; i < suffix.size(); i++) {
            permute(prefix + suffix[i], suffix.substr(0,i) + suffix.substr(i + 1), res);
        }
    }
    
    
    int main(){
        string str = "123";
        vector<string> res;
        permute("", str, res);
    }
    

    The function collects all permutations in vector res. The idea can be generalized for different type of containers using templates and iterators:

    template <typename Cont1_t, typename Cont2_t>
    void permute(typename Cont1_t prefix,
        typename Cont1_t::iterator beg, typename Cont1_t::iterator end,
        Cont2_t &result)
    {
        if (beg == end) {
            result.insert(result.end(), prefix);
            return;
        }
        for (auto it = beg; it != end; ++it) {
            prefix.insert(prefix.end(), *it);
            Cont1_t tmp;
            for (auto i = beg; i != end; ++i)
                if (i != it)
                    tmp.insert(tmp.end(), *i);
    
            permute(prefix, tmp.begin(), tmp.end(), result);
            prefix.erase(std::prev(prefix.end()));
        }
    }
    
    int main()
    {
        string str = "123";
        vector<string> rStr;
        permute<string, vector<string>>("", str.begin(), str.end(), rStr);
    
        vector<int>vint = { 1,2,3 };
        vector<vector<int>> rInt;
        permute<vector<int>, vector<vector<int>>>({}, vint.begin(), vint.end(), rInt);
    
        list<long> ll = { 1,2,3 };
        vector<list<long>> vlist;
        permute<list<long>, vector<list<long>>>({}, ll.begin(), ll.end(), vlist);
    }
    

    This may be an interesting programming exercise, but in production code you should use a non recusrive version of permutation , like next_permutation.

    0 讨论(0)
  • 2020-11-27 11:49

    Actually you can do it using Knuth shuffling algo!

    // find all the permutations of a string
    // using Knuth radnom shuffling algorithm!
    
    #include <iostream>
    #include <string>
    
    template <typename T, class Func>
    void permutation(T array, std::size_t N, Func func)
    {
        func(array);
        for (std::size_t n = N-1; n > 0; --n)
        {
            for (std::size_t k = 0; k <= n; ++k)
            {
                if (array[k] == array[n]) continue;
                using std::swap;
                swap(array[k], array[n]);
                func(array);
            }
        }
    }
    
    int main()
    {
        while (std::cin.good())
        {
            std::string str;
            std::cin >> str;
            permutation(str, str.length(), [](std::string const &s){ 
                std::cout << s << std::endl; });
        }
    }
    
    0 讨论(0)
  • 2020-11-27 11:49

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

    0 讨论(0)
提交回复
热议问题