Search code examples
c++recursionpermutationrecurrence

Recurssion issue in generating permutation in c++


i have two n in c++ and i want to generate permutation of the numbers in those vectors in such a way for each permutation of the first vector i have all the permutations of all the other vectors. Say i have two vectors with number 2 9 and the other vector will be 5 6. then my result should be...

  1. 2 9 5 6
  2. 2 9 6 5
  3. 9 2 5 6
  4. 9 2 6 5

means that the total number of permutations i have got will be total perms = (# of permutations of the 1st vector times number of permutations of the second vector times number of permutations of the third vector and so on).

I have written the below code and i am struck in to recursion stack... It is actually printing 6 times for the case of 2 vectors each have the size of 2 each.

mySwap(int *x, int *y){
int temp;
temp = *x;
    *x = *y;
*y = temp;
}

swaps the two int elements

void myPerm(vector<vector<int>> myItems, int start, int end,int     vectorIndex){
int j;
if(start == end){
    for(int k = vectorIndex +1; k < items.size(); ++k){
        myPerm(myItems, 0, myItems[k].size()-1,k);
    }
    for(int z = 0; z < myItems.size(); ++z){
        for(int l = 0; l < myItems[z].size(); ++z){
            std::cout << myItems[z][l];
        }
    }
}
else{
    for(int j = start; j <= end; j++){
        mySwap(&myItems[vectorIndex][start],&myItems[vectorIndex][j]);
        myPerm(myItems,start + 1, end,vectorIndex);
        mySwap(&myItems[vectorIndex][start],&myItems[vectorIndex][j]);

    }   

}
} 

above code that generates permutations recursively...

int main(){
vector<vector<int>> myItems;
int k = 0;
for(int i =0; i < 2; ++i){
    myItems.push_back(vector<int>);
}
for(int j =0; j < 2; ++j){
    myItems[i].push_back(k++);
}

myPerm(items,0,items[0].size()-1,0);
return;
}

my main function.

Please give me some hint or solve this this for the generic case as the above code prints the permutations for the six which originally should be 4 times.

Thanks


Solution

  • Thanks for all the ideas specially for the STL function next_permutation. I don't know it earlier.

    I was able to write the code i want it correctly...

    Here is my code

    void perm(std::vector<std::vector <int>> &items, int level){
    if(level == 0){
    for (int i = 0; i < items.size(); i++)
      for (int j = 0; j < items[i].size(); j++)
          std::cout << items[i][j];
    std::cout<<std::endl;
    
    
        while(next_permutation(items[level].begin(), items[level].end())){
            for (int i = 0; i < items.size(); i++)
              for (int j = 0; j < items[i].size(); j++)
                  std::cout << items[i][j];
            std::cout<<std::endl;
        }
    }
    else{
    
        if(level > 0)
        perm(items,level-1);
        while(next_permutation(items[level].begin(), items[level].end())){
            if(level > 0)
            perm(items,level-1);
        }
    
    }
    

    }