I’m having some difficulty converting this recursive algorithm for displaying all the permutations of a given set of integers into an iterative one.
void getPermutationsR(int v[], int n, int i)
{
if (i == n)
{
//Display contents of v
}
else
{
for (int j=i; j<n; j++)
{
swap (v, i, j);
getPermutationsR(v, n, i+1);
swap (v, i, j);
}
}
}
This is my current attempt, it’s completely wrong but I can’t see any way to correct it without using a natively iterative algorithm for the problem . Half my attempts have had me ‘popping’ more than ‘pushing’ (Leads to an error as I attempt to access elements in an empty stack) and the other half I’m ‘pushing’ more than ‘popping’ (infinite loop).
void getPermutationsI(int v[], int n, int i)
{
stack<int> iStack;
stack<int> jStack;
iStack.push(i);
jStack.push(i);
while(iStack.size() > 0)
{
if (iStack.top() == n)
{
jStack.pop();
iStack.pop();
//Display contents of v
}
else
{
for (int j = iStack.top(); j < n; j++)
{
//swap
//something to do with jStack
}
//swap
iStack.push(i+1);
}
}
}
The challenge you are encountering is that you’ve got function calls and loop constructs intermingled. It is hard to disentangle those.
First let’s start by replacing all control of flow operations with recursion.
Next let’s add more state so that we only have one recursive call inside of an if condition.
Now that we’ve accomplished this, we have it in a form where we can transform it into an iterative version in a straightforward way. Here is the transformation
becomes
So applying that pattern we get something like:
(Warning, all code untested, and may well not even compile. But the idea is correct. And it is definitely the same algorithm.)