Monday, March 14, 2011

Get all permutations - C++ code

All right today I am presenting some C++ code that gets all the permutations of a list of items. The code is based in the following function:
----------------------------------

#include <vector>
using namespace std;


vector<vector<int>> GetAllPermutations(vector<int> indexes, vector<int> prev)
{
vector<vector<int>> permutations;


if(indexes.size() == 0)
{
permutations.push_back(prev);
}


for (int i = 0; i < indexes.size(); i++)
{
int first = indexes[0];
int ith = indexes[i];
indexes[i] = first;
indexes.erase(indexes.begin());


prev.push_back(ith);
vector<vector<int>> thisPermutations = GetAllPermutations(indexes, prev);
prev.pop_back();
permutations.insert(permutations.end(), thisPermutations.begin(), thisPermutations.end());
indexes.insert(indexes.begin(), ith);
}


return permutations;
}

----------------------------------


Below a couple of examples of functions using the method above:

----------------------------------
void Run1()
{
int n = 6;
vector<int> items;
for(int i = 0; i < n; i++)
{
items.push_back(i);
}
vector<int> prev;
vector<vector<int>> permut = GetAllPermutations(items,prev);
for(int i = 0; i < permut.size(); i++)
{
for(int j = 0; j < permut[i].size(); j++)
{
printf("%d,", permut[i][j]);
}
printf("\n");
}
}

----------------------------------

----------------------------------
void Run2()
{
vector<string> items;
items.push_back("ant");
items.push_back("bear");
items.push_back("cat");
items.push_back("deer");
items.push_back("elephant");
//items.push_back("fox");

vector<int> indexes;
for(int i = 0; i < items.size(); i++)
{
indexes.push_back(i);
}
vector<int> prev;
vector<vector<int>> permut = GetAllPermutations(indexes,prev);
for(int i = 0; i < permut.size(); i++)
{
for(int j = 0; j < permut[i].size(); j++)
{
int index = permut[i][j];
printf("%s,", items[index].c_str());
}
printf("\n");
}
}
----------------------------------
Run it and it will print all the permutations of the items in the list:
----------------------------------
int main()
{
//Run1();
Run2();
}
----------------------------------
and so on...

MArio

No comments:

Post a Comment