I would like to ask all my fellow programmers regarding only efficiency. I am currently solving problems that could be asked in job interviews and I’ve come across with the famous permutations of a string. The code I’ve written below might be the most common thing in programming history, however, I do not know it’s status since I haven’t checked for any solution.
Long story would the short the program I’ve coded below be a suitable solution? Or can it be made even more efficient. Asking because if I came across one day I would like to be sure that I’ve implement one of the best approaches for this problem.
#include <iostream>
using namespace std;
int fac(int num)
{
int result=1;
for(int i=1;i<=num;i++)
result*=i;
return result;
}
int main(int argc, const char * argv[])
{
string str="abcd";
int limit=fac(str.size());
int mod=str.size();
for(int i=0;i<limit;i++){
swap(str[i%mod],str[(i+1)%mod]);
cout<<str<<endl;
}
return 0;
}
I’ve figured out the solution by using a
std::map. Don’t think it is that inefficient;