Write a modularized C++ program that will recursively generate all the permutati
ID: 639576 • Letter: W
Question
Write a modularized C++ program that will recursively generate all the permutations of any given n distinct objects (in this case use characters). For this project, use n = 6 as the maximum value for n, but your program should have the ability to work for any value of n with minimal code modification. (Note: this program will require a recursive routine that has a loop in it.)
Prompt the user interactively for the character data. At the least verify that the following are correctly permuted
1)H I
2)1 2 3
3)P S L V
4)@ # $ % &
Place the output in a file and inform the user the name of the file before exiting. Here is an example of an output file:
Enter the number of characters you want to permute => 3
Enter 3 characters => 1 2 3
Permutation 1: 1 2 3
Permutation 2: 1 3 2
Permutation 3: 2 1 3
Permutation 4: 2 3 1
Permutation 5: 3 2 1
Permutation 6: 3 1 2
Explanation / Answer
#include<iostream>
using namespace std;
/* Function to swap two characters */
void swap(char& a, char& b)
{
char temp;
temp = a;
a = b;
b = temp;
}
/* Function to obtain permutations of string characters */
void permutation(string s,int i,int n)
{
int j;
static int k=1;
if (i == n)
cout <<" Permutation "<<k++<<" : "<<s << " ";
else
{
for (j = i; j < s.length(); j++)
{
swap(s[i],s[j]);
permutation(s, i + 1, n);
swap(s[i],s[j]);
}
}
}
int main()
{
string s;
int n;
cout<<"enter the number of characters you want to permute=> ";
cin>>n;
cout << " Enter "<<n<<"characters=> ";
cin >> s;
permutation(s, 0, s.length() - 1);
cout << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.