Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR 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;
  }
}
 
PREVIOUS NEXT
Tagged: #permutations #characters
ADD COMMENT
Topic
Name
6+2 =