I have pairs (a1,b1) , (a2, b2) ..... (an,bn) I want to generate all the 2^n lists. With recursion this is easy and is like finding all permutations of string however I want to do it iteratively. Please suggest me a way to do this.
To be clear the first place of list can be a1 or b1 the second place can be a2 or b2 .. the ith place can be ai or bi....the nth place will be an or bn.
Example: (a1 a2 .... an) (b1 b2 ..... bn) (b1 a2 ...an) (a1 b2 .....an) (all 2^n lists)
here is a sample recursive code for n=3.
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
void compute( int a[][2],int i,vector<int> v)
{
if(i==3)
{
for(int j=0;j<v.size();j++)
cout<<v[j]<<" ";
cout<<endl;
return;
}
for(int j=0;j<=1;j++)
{
if(j==1) v.pop_back();
v.push_back(a[i][j]);
compute(a,i+1,v);
}
}
int main()
{
float ans=0;
int a[3][2];
for(int i=0;i<=2;i++)
{
for(int j=0;j<=1;j++)
cin>>a[i][j];
}
vector <int> v;
compute(a,0,v);
}
I want to use iterative code to improve performance both in terms of speed and more importantly on space because now I have to pass by value so the new vector v is being created every time and the code will not work if I pass by reference