Premute string

darkscript 0 Tallied Votes 566 Views Share

Gives different combinations(Permutations) of string in input

//Gives different combinations(Permutations) of string in input

#include <iostream>
#include <string.h>
#include <vector>

using namespace std;

char* Move (char*, int, int);

char* Move (char* Str,int From, int To)
{
	if (strlen (Str) < From || strlen (Str) < To)
		return 0;
	else
	{
		char* tmpStr = new char [strlen (Str)];
		strcpy (tmpStr, Str);
		tmpStr [To] = Str [From];
		tmpStr [From] = Str [To];
		return tmpStr;
	}
		
}

int main (int argc, char* argv[])
{
	for (int i=1; i<argc; i++)
	{
		//Take each char in input
		//Put it in every position in input
		//i.e. length of input is 4
		//we take 1st char put it in 1st place
		//1st char in 2nd place, in 3rd place, in 4th place
		//then we take the 2nd char and do the same thing

		vector <char*> results;

		for (int l=0; l<strlen (argv [i]); l++)
		{
			//cout << "Currently processing character : " << argv [i][l] << endl;
			
			for (int j=0; j<strlen (argv [i]); j++)
			{
				bool valid = true;
				char* tmp = Move (argv [i], l, j);
				for (int k=0; k<results.size(); k++)
				{
					if (strcmp (tmp, results[k]) == 0)
						valid = false;
				}
				if (valid)
				{
					results.push_back (tmp); 
					cout << "After moving : " << argv[i][l] << " from " << l+1 << " Place, to " << j+1 << " Place, We get : " << tmp << endl;
				}
			}
		}
	}
}
ShawnCplus 456 Code Monkey Team Colleague

If your function is defined above main you don't need the prototype.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.