In: Computer Science
----------------
Exercise 2: String Permutations
----------------
Create a program that takes a string from the command line and prints every permutation of that string. You may assume the string will contain all unique characters. You may print the permutations in any order, as long as you print them all.
----------------
Output:
----------------
$>./prog dog d do dog dg dgo o od odg og ogd g gd gdo go god
----------------
I need help on this exercise that requires recursion only. I need main.cpp, makefile, Executive.cpp, and Executive.h files for this exercise, and I have no idea how to code this recursive exercise. So, will someone help me on this exercise?
Hello dear student..as required by you the code for string permutations is given below.
You can run a save the code as .cpp file and get what you need. I am sure this will work. If you have any doubts after that..please ask in the comments..i will be happy to answer.
// C++ program to print all
// permutations with duplicates allowed
#include <bits/stdc++.h>
using namespace std;
// Function to print permutations of string
// This function takes three parameters:
// 1. String
// 2. Starting index of the string
// 3. Ending index of the string.
void permute(string a, int l, int r)
{
// Base case
if (l == r)
cout<<a<<endl;
else
{
// Permutations made
for (int i = l; i <= r; i++)
{
// Swapping done
swap(a[l], a[i]);
// Recursion called
permute(a, l+1, r);
//backtrack
swap(a[l], a[i]);
}
}
}
// Driver Code
int main()
{
string str = "ABC";
int n = str.size();
permute(str, 0, n-1);
return 0;
When you run this , you will find all the permitations of string ABC as output.
Regards.