I wrote this code to help with programming challenges. A lot of problems can be solved by complete search so I wrote this function that I can copy/paste between problems to generate permutations quickly. Does anyone have any comments or suggestions to improve this function?
bool bruteforceGenerator(string& permutationIn, const vector<char>& options, const int maxLength)
{
if(permutationIn.size() == 0) // In case we begin with a blank string just return the starting case
{
permutationIn = options[0];
return true;
}
else
{
// First try to increment any digit in the string starting from the right
for(int i = permutationIn.size() - 1; i>=0; i--)
{
if(permutationIn[i] != options[options.size()-1]) // If we can increment any digit
{
// Increment the individual digit
auto index = find(options.begin(), options.end(), permutationIn[i]);
permutationIn[i] = *(index+1);
// Set all the digits after i back to their start values
for(int j = i+1; j<permutationIn.size(); j++)
{
permutationIn[j] = options[0];
}
return true;
}
}
if(permutationIn.size() < maxLength) // If we could not increment a digit perhaps we could still make the string longer
{
permutationIn.push_back(0);
for(auto &i : permutationIn) i = options[0];
return true;
}
else return false; // If we could not increment any digit and we could not make the string any longer then we are out of permutations
}
}
The return type of the function was chosen to allow usage of the function to look something like
string permutation;
vector <char> options {'^','v','<','>'};
while(bruteforceGenerator(permutation, options, 2))
{
// Do something with the permutation
}
Sample output:
^
v
<
>
^^
^v
^<
^>
v^
vv
v<
v>
<^
<v
<<
<>
>^
>v
><
>>