Search
 
SCRIPT & CODE EXAMPLE
 

CPP

all possible permutations of characters in c++

/* 
You need to pass this function a vector containing characters that you want to 
get all permutations of, an integer which equals to 0, and empty vector.
then create a vector outside the function called 'allPermutations', and
it is gonna get filled up with all possible permutations, which will all be 
saved in vectors.
*/
#include <bits/stdc++.h>
using namespace std;

vector<vector<char>> allPermutations; // vector where you get all permutations

void perm(vector<char> vec,int curr,vector<char> currentPerm){
    if(currentPerm.size() == vec.size()){
        allPermutations.push_back(currentPerm);
        return;
    }
    char r = vec[curr];
    if(currentPerm.size() == 0){
        currentPerm.push_back(r);
        perm(vec,curr+1,currentPerm);
        return;
    }
    int cnt = 0;
    while(cnt <= currentPerm.size()){
        vector<char> temp;
        for(int i = 0; i < currentPerm.size(); i++){
            if(i == cnt)temp.push_back(r);
            temp.push_back(currentPerm[i]);
        }
        if(cnt == currentPerm.size())temp.push_back(r);
        perm(vec,curr+1,temp);
        cnt++;
    }
}
int main(){
  vector<char> vec = {'1','2','3','4'};
  vector<char> empty;
  perm(vec,0,empty);
  for(auto it : allPermutations){
      for(auto itt : it){
          cout << itt << " ";
      }
      cout << endl;
  }
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: aray of functions in c++ 
Cpp :: string to char* 
Cpp :: matrix transpose in c++ 
Cpp :: print 2d array c++ 
Cpp :: how to rotate canvas android 
Cpp :: c++ reference 
Cpp :: how to send email in c++ program 
Cpp :: c++ default parameters 
Cpp :: how to print in cpp 
Cpp :: continue c++ 
Cpp :: tolower funciton in cpp 
Cpp :: how to delete a file in cpp 
Cpp :: how to return char* from function in c++ 
Cpp :: break in c++ 
Cpp :: how to sort in descending order in c++ 
Cpp :: filling 2d array with 0 c++ 
Cpp :: c++ logger class example 
Cpp :: comparator in sort c++ 
Cpp :: inline in class in C++ 
Cpp :: cpp print variable value 
Cpp :: how to find min of two numbers in c++ 
Cpp :: c++ string find example 
Cpp :: best websites for programming 
Cpp :: sort c++ 
Cpp :: c++ thread 
Cpp :: c++ multiple inheritance 
Cpp :: stl c++ 
Cpp :: structure of a function in C++ 
Cpp :: system cpp 
Cpp :: standard template library in c++ 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =