jeudi 26 octobre 2017

stacks and queues for generating permutations (without recursion)

Assume that i have defined two classes for stacks and queues. I want to define a method that takes a parameter as list, and returns all permutations of that list. Effectively, I only want to use a single stack and queue to fulfill this task.

I think that you pop the top of the stack and place it in the queue. After that you continue poping the top of the stack until the front of the queue is bigger than the top of the stack. When this happens, you should pop the top of the stack, place the front of the queue on the stack, place the top of the stack right after it in the stack and then add the other elements from the queue in the order they would appear from the queue.

I do not know how to execute this in code. If there is a better way, please advise on how i would do this (without recursion).

   #include <iostream>
   #include <vector>

   using namespace std;

   void gen(vector<int> & permutation, int level, int n)
 {
int i;
if(level==n)
{
    for(i=0;i<n;i++)
        cout<<permutation[i];
    cout<<endl;
}
else
{
    for(i=0;i<=level;i++)
    {
        vector<int>  p(permutation);   //What does this do?
        p.insert(p.begin()+i,level);      //And what is happening here?
        gen(p,level+1,n);
    }
}

}

int main()
{
int n;
cin>>n;

vector<int> permutation;
gen(permutation,0,n);
return 0;

}

Aucun commentaire:

Enregistrer un commentaire