Print all permutations of a string in c++

C++ program for Print all permutations of a string. Here problem description and other solutions.

// Include header file
#include <iostream>
#include <string>
using namespace std;
// C++ program for
// Print all permutations of a string
class Permutation
{
	public:
		// Swapping two string elements by index
		string swap(string text, int size, int a, int b)
		{
			if ((a >= 0 && a < size) && (b >= 0 && b < size))
			{
				//When valid a and b location
				char temp = text[a];
				text[a] = text[b];
				text[b] = temp;
			}
			// return modified result
			return text;
		}
	// Method which is print all permutations of given string
	void findPermutation(string text, int n, int size)
	{
		if (n > size)
		{
			return;
		}
		if (n == size)
		{
			cout << text << endl;
			return;
		}
		for (int i = n; i < size; ++i)
		{
			// Swap the element
			text = this->swap(text, size, i, n);
			this->findPermutation(text, n + 1, size);
			// Swap the element
			text = this->swap(text, size, i, n);
		}
	}
};
int main()
{
	Permutation *task = new Permutation();
	string text = "ABC";
	int size = text.length();
	task->findPermutation(text, 0, size);
	cout << endl;
	text = "abcd";
	size = text.length();
	task->findPermutation(text, 0, size);
	return 0;
}

Output

ABC
ACB
BAC
BCA
CBA
CAB

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved