I have bee trying to work this out for a couple of hours now, I am getting nowhere and its annoying.
Here is some working code to display string permutations in C++:
Code:
#include <iostream>
#include <string>
using namespace std;
string swtch(string topermute, int x, int y)
{
string newstring = topermute;
newstring[x] = newstring[y];
newstring[y] = topermute[x]; //avoids temp variable
return newstring;
}
void permute(string topermute, int place)
{
if(place == topermute.length() - 1)
{
cout<<topermute<<endl;
}
for(int nextchar = place; nextchar < topermute.length(); nextchar++)
{
permute(swtch(topermute, place, nextchar), place+1);
}
}
int main()
{
permute("love", 0);
system("PAUSE");
}
I tried to convert this to C. Here is what I got:
Code:
#include <stdio.h>
#include <string.h>
char *CharSwap(char *word, int x, int y)
{
char temp = word[x];
word[x] = word[y];
word[y] = temp;
return word;
}
void Permute(char *word, int pos)
{
int len=strlen(word);
int next;
if(pos == len-1)
printf("%s\n", word);
for(next=pos; next<len; next++)
Permute(CharSwap(word, pos, next), pos+1);
}
int main()
{
char word[]="love";
Permute(word, 0);
system("PAUSE");
}
If someone could please explain why the second version in C does not work correctly it would be much appreciated by me. Thanks.