In: Computer Science
11.10 LAB: All permutations of names
PLEASE ANSWER IN C++!
Write a program that lists all ways people can line up for a photo (all permutations of a list of strings). The program will read a list of one word names (until -1), and use a recursive method to create and output all possible orderings of those names, one ordering per line.
When the input is:
Julia Lucas Mia -1
then the output is (must match the below ordering):
Julia Lucas Mia Julia Mia Lucas Lucas Julia Mia Lucas Mia Julia Mia Julia Lucas Mia Lucas Julia
----File: main.cpp----
#include <vector>
#include <string>
#include <iostream>
using namespace std;
// TODO: Write method to create and output all permutations of
the list of names.
void AllPermutations(const vector<string> &permList,
const vector<string> &nameList) {
}
int main(int argc, char* argv[]) {
vector<string> nameList;
vector<string> permList;
string name;
// TODO: Read in a list of names; stop when -1 is read. Then
call recursive method.
return 0;
}
I added another parameter to AllPermutation function -"len" which represents the swapping position.
code in text-
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
// Write method to create and output all permutations of the list of names.
void AllPermutations( vector<string> &permList, vector<string> &nameList,int len) {
//when full swapping is done
if (len == nameList.size()-1) {
for (int i = 0; i < nameList.size(); i++) {
cout << nameList[i] << " ";
permList.push_back(nameList[i]);
}
cout << endl;
}
else
{
// for Permutations
for (int i = len; i <= nameList.size()-1; i++)
{
// Swapping
swap(nameList[len], nameList[i]);
// Recursion called
AllPermutations(permList,nameList, len+1);
//back swapping
swap(nameList[len], nameList[i]);
}
}
}
int main(int argc, char* argv[]) {
vector<string> nameList;
vector<string> permList;
string name;
// Read in a list of names; stop when -1 is read. Then call recursive method.
string a="0";//for -1;
while (a!="-1"){
cin >> a;
if(a!="-1"){
nameList.push_back(a);
}
}
int len=0;//for swapping while caluclating
AllPermutations(permList,nameList,len);
return 0;
}
screen shot of code


output-

If you like this answer please give an UPVOTE, if you have any query feel free to ask in comment section.