173k views
1 vote
#include

#include
#include
using namespace std;
void PrintAllPermutations(vector &permList, vector &nameList) {
vector tmpVec;
if (nameList.size() == 0) {
for (size_t i = 0; i < permList.size(); ++i) {
cout << permList.at(i);
if (i < permList.size() - 1) {
cout << ", ";
}
}
cout << endl;
}
else {
for (size_t i = 0; i < nameList.size(); ++i) {
tmpVec = nameList;
permList.push_back(tmpVec.at(i));
tmpVec.erase(tmpVec.begin() + i);
PrintAllPermutations(permList, tmpVec);
permList.pop_back();
}
}
}
int main() {
vector nameList;
vector permList;
string name;
while (true) {
cin >> name;
if (name == "-1") { break; }
nameList.push_back(name);
}
PrintAllPermutations(permList, nameList);
return 0;
}
// Can you explain to me how this code works
// INPUT:
// Julia Lucas Mia -1
/*
Output:
Julia, Lucas, Mia
Julia, Mia, Lucas
Lucas, Julia, Mia
Lucas, Mia, Julia
Mia, Julia, Lucas
Mia, Lucas, Julia
*/

User Edo Akse
by
7.7k points

1 Answer

5 votes

Final answer:

The given code is an implementation of a recursive function that prints all permutations of a given list of names. It uses vector data structures to store the list of names and the current permutation being constructed.

Step-by-step explanation:

The given code is an implementation of a recursive function that prints all permutations of a given list of names. It uses vector data structures to store the list of names and the current permutation being constructed. The function PrintAllPermutations takes two vector parameters: permList (the current permutation) and nameList (the remaining names to be added to the permutation).

When the nameList is empty, it means all names have been added to the current permutation. In this case, the function prints the permutation by iterating over the elements in permList and printing them separated by commas. When the nameList is not empty, the function recursively calls itself with a modified permList and nameList. It adds one name from nameList to permList, removes that name from nameList, and calls the function again.

The main function reads names from the user until the user enters '-1' as the name. It then calls PrintAllPermutations with an empty permList and the list of names read.

User Piovezan
by
9.2k points